@ultimat3/cli 31.50.0 → 31.51.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.
package/CLAUDE.md CHANGED
@@ -87,7 +87,7 @@ Commands: `bun test ./packages/cli/` (repo root: the preload),
87
87
  | `i18n-app-key-shapes.ts` | every shape whose literal is a catalog key; `i18n-app-key-shapes.test.ts` reads `blocks`, so a new block reds until listed |
88
88
  | `job-budget.ts` | `X_JOB_OUTLASTS_DRAIN` (`manifest`): `timeout` vs `workerBudgetMs(drain)`, from the registry † |
89
89
  | `output-findings.ts` | render layer only: `runnableFix` (`bunx x`, decided by `dispatch.ts`'s `readerFor`) and `collapseFindings`. Throw sites keep `x …` |
90
- | `app-load-unresolved.ts` | `X_APP_IMPORT_UNRESOLVED`, read by the scan, `findingFrom` and `x doctor`'s `snapshots` probe |
90
+ | `app-load-{unresolved,import-chain}.ts` / `app-dev-imports.ts` | `X_APP_IMPORT_UNRESOLVED`; `X_BOUNDARY_DEV_IMPORT` † |
91
91
  | `fix-truth*.ts` / `db-fix-truth.job.test.ts` | a printed fix, executed against a broken scaffold † |
92
92
 
93
93
  ### Generators (`x g`, `x new`)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/cli",
3
- "version": "31.50.0",
3
+ "version": "31.51.0",
4
4
  "description": "The `x` binary: new, dev, build, verify, generate, db, mcp, doctor, deploy",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -53,34 +53,34 @@
53
53
  },
54
54
  "dependencies": {
55
55
  "@babel/core": "^8.1.0",
56
- "@ultimat3/action": "31.50.0",
57
- "@ultimat3/admin": "31.50.0",
58
- "@ultimat3/ai": "31.50.0",
59
- "@ultimat3/auth": "31.50.0",
60
- "@ultimat3/cache": "31.50.0",
61
- "@ultimat3/core": "31.50.0",
62
- "@ultimat3/db": "31.50.0",
63
- "@ultimat3/entity": "31.50.0",
64
- "@ultimat3/flags": "31.50.0",
65
- "@ultimat3/http": "31.50.0",
66
- "@ultimat3/i18n": "31.50.0",
67
- "@ultimat3/jobs": "31.50.0",
68
- "@ultimat3/mail": "31.50.0",
69
- "@ultimat3/manifest": "31.50.0",
70
- "@ultimat3/mcp": "31.50.0",
71
- "@ultimat3/money": "31.50.0",
72
- "@ultimat3/notify": "31.50.0",
73
- "@ultimat3/policy": "31.50.0",
74
- "@ultimat3/pwa": "31.50.0",
75
- "@ultimat3/query": "31.50.0",
76
- "@ultimat3/realtime": "31.50.0",
77
- "@ultimat3/render": "31.50.0",
78
- "@ultimat3/schema": "31.50.0",
79
- "@ultimat3/scraping": "31.50.0",
80
- "@ultimat3/seo": "31.50.0",
81
- "@ultimat3/storage": "31.50.0",
82
- "@ultimat3/testing": "31.50.0",
83
- "@ultimat3/time": "31.50.0",
56
+ "@ultimat3/action": "31.51.0",
57
+ "@ultimat3/admin": "31.51.0",
58
+ "@ultimat3/ai": "31.51.0",
59
+ "@ultimat3/auth": "31.51.0",
60
+ "@ultimat3/cache": "31.51.0",
61
+ "@ultimat3/core": "31.51.0",
62
+ "@ultimat3/db": "31.51.0",
63
+ "@ultimat3/entity": "31.51.0",
64
+ "@ultimat3/flags": "31.51.0",
65
+ "@ultimat3/http": "31.51.0",
66
+ "@ultimat3/i18n": "31.51.0",
67
+ "@ultimat3/jobs": "31.51.0",
68
+ "@ultimat3/mail": "31.51.0",
69
+ "@ultimat3/manifest": "31.51.0",
70
+ "@ultimat3/mcp": "31.51.0",
71
+ "@ultimat3/money": "31.51.0",
72
+ "@ultimat3/notify": "31.51.0",
73
+ "@ultimat3/policy": "31.51.0",
74
+ "@ultimat3/pwa": "31.51.0",
75
+ "@ultimat3/query": "31.51.0",
76
+ "@ultimat3/realtime": "31.51.0",
77
+ "@ultimat3/render": "31.51.0",
78
+ "@ultimat3/schema": "31.51.0",
79
+ "@ultimat3/scraping": "31.51.0",
80
+ "@ultimat3/seo": "31.51.0",
81
+ "@ultimat3/storage": "31.51.0",
82
+ "@ultimat3/testing": "31.51.0",
83
+ "@ultimat3/time": "31.51.0",
84
84
  "babel-preset-solid": "^1.9.16"
85
85
  }
86
86
  }
@@ -40,6 +40,8 @@ export const BOUNDARY_CODES = [
40
40
  'X_BOUNDARY_LOADER_IMPORT',
41
41
  // `package-boundaries.ts`'s: it reads `packages/`, which this module's surface graph never holds.
42
42
  'X_BOUNDARY_PACKAGE_TO_APP',
43
+ // `app-dev-imports.ts`'s: a warning on `main`, over what the boot scan imports.
44
+ 'X_BOUNDARY_DEV_IMPORT',
43
45
  ] as const;
44
46
 
45
47
  export type BoundaryCode = (typeof BOUNDARY_CODES)[number];
@@ -0,0 +1,77 @@
1
+ // `X_BOUNDARY_DEV_IMPORT`: what the boot scan imports reaches no development entry. A test helper
2
+ // under `app/` is an app module, and one brought `@ultimat3/cli`'s barrel into every role, the gate
3
+ // green. A WARNING on `main` (X_BREAKING_ON_MAIN); the refusal lands on `next`.
4
+
5
+ // why: Bun ships no path API; the marker of an app root is read at a joined path.
6
+ import { join, resolve } from 'node:path';
7
+ import { APP_CONFIG_FILE, ERROR_DOCS_URL } from '@ultimat3/core';
8
+ import { realPath } from './app-load-unresolved';
9
+ import { devOnlyCut, devOnlyFix, isDevOnlySpecifier, scannedModules } from './dev-only-imports';
10
+ import type { EvaluatedImport, WalkVerdict } from './evaluated-walk';
11
+ import { createEvaluatedGraph } from './evaluated-walk';
12
+ import type { Finding } from './output';
13
+ import { hasPathSegment, isPathUnder } from './path-segments';
14
+ import { posixRelative } from './posix-path';
15
+ import { scanWays } from './scan-ways';
16
+
17
+ /** One finding per cut the app owes a development import its boot evaluates, in path order. */
18
+ export async function devImportFindings(root: string): Promise<readonly Finding[]> {
19
+ // An app only: the framework monorepo has no boot scan, and its `packages/cli` IS the barrel.
20
+ if (!(await Bun.file(join(root, APP_CONFIG_FILE)).exists())) return [];
21
+ const base = realPath(resolve(root));
22
+ const scanned = await scannedModules(base);
23
+ const named = (path: string): string => posixRelative(base, path);
24
+ const found: EvaluatedImport[] = [];
25
+ const followed: EvaluatedImport[] = [];
26
+ const judge = (edge: EvaluatedImport): WalkVerdict => {
27
+ if (isDevOnlySpecifier(edge.specifier)) {
28
+ found.push(edge);
29
+ return 'skip';
30
+ }
31
+ // The app's own modules only: an installed package answers for its own graph.
32
+ const target = edge.target();
33
+ const own =
34
+ target !== undefined &&
35
+ isPathUnder(base, target) &&
36
+ !hasPathSegment(named(target), 'node_modules');
37
+ if (!own) return 'skip';
38
+ followed.push(edge);
39
+ return 'follow';
40
+ };
41
+ await createEvaluatedGraph().walk([...scanned], judge);
42
+ const ways = scanWays(
43
+ found.map((edge) => edge.from),
44
+ scanned,
45
+ followed,
46
+ );
47
+ const findings = new Map<string, Finding>();
48
+ for (const { from, specifier } of found) {
49
+ for (const steps of ways(from)) {
50
+ const cut = devOnlyCut(steps, scanned);
51
+ const chain = steps.map((step) => named(step.path));
52
+ const at = chain[cut.index] ?? named(from);
53
+ const via = chain.length === 1 ? '' : ` (${chain.join(' → ')})`;
54
+ const finding: Finding = {
55
+ code: 'X_BOUNDARY_DEV_IMPORT',
56
+ cause: `the boot scan imports ${named(from)}${via}, and it imports "${specifier}", a development entry: an image that leaves the test packages out boots no role`,
57
+ fix: devOnlyFix(at, cut, specifier),
58
+ docs: ERROR_DOCS_URL,
59
+ at,
60
+ meta: { specifier, chain },
61
+ };
62
+ // One import written twice in a module is one edit: the same line finds both.
63
+ findings.set(
64
+ [at, chain.join('\u0000'), specifier, finding.fix].join('\u0000\u0000'),
65
+ finding,
66
+ );
67
+ }
68
+ }
69
+ return [...findings].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([, one]) => one);
70
+ }
71
+
72
+ /** What the `boundaries` step carries on `main`: one line per finding, advice and never red. */
73
+ export async function devImportWarnings(root: string): Promise<readonly string[]> {
74
+ return (await devImportFindings(root)).map(
75
+ (finding) => `${finding.code} ${finding.cause} — fix: ${finding.fix}`,
76
+ );
77
+ }
@@ -0,0 +1,112 @@
1
+ // An import that failed inside an installed package, explained from the app's side: the app module
2
+ // that pulled the package in, the chain to the failing import, and the edit or install that clears
3
+ // it. The bare finding names a file under `node_modules`, which no reader can edit.
4
+ // Loaded only when a load has already failed (`app-load.ts`).
5
+
6
+ // why: Bun ships no path API; the failing module is named app-root-relative and walked absolute.
7
+ import { resolve } from 'node:path';
8
+ import type { UnresolvedImport } from './app-load-unresolved';
9
+ import { realPath, unresolvedImport } from './app-load-unresolved';
10
+ import type { DevOnlyCut } from './dev-only-imports';
11
+ import { devOnlyCut, devOnlyFix, isDevOnlySpecifier, scannedModules } from './dev-only-imports';
12
+ import type { ChainStep } from './evaluated-walk';
13
+ import { createEvaluatedGraph } from './evaluated-walk';
14
+ import type { Finding } from './output';
15
+ import { findingFrom } from './output';
16
+ import { hasPathSegment, isPathUnder } from './path-segments';
17
+ import { posixRelative } from './posix-path';
18
+
19
+ /** `…/node_modules/@ultimat3/cli/src/index.ts` → `@ultimat3/cli/src/index.ts`, under any linker. */
20
+ const shown = (path: string): string => path.replace(/^.*\bnode_modules\//, '');
21
+
22
+ /** What the app does to reach the package: the module to edit, its import, and the way down. */
23
+ interface Entry {
24
+ readonly at: string;
25
+ readonly specifier: string;
26
+ /** App-root-relative: the module to edit first, the failing module last. */
27
+ readonly chain: readonly string[];
28
+ /** The import by which the chain leaves the app: `specifier`, unless the edit is further up. */
29
+ readonly leavesBy: string;
30
+ /** The gate's own cut, when the import that leaves the app is one no role may load. */
31
+ readonly cut?: DevOnlyCut;
32
+ }
33
+
34
+ /**
35
+ * The last module of the app's own on the chain, and what it imports out of the app. When that is a
36
+ * development entry the edit is the gate's (`devOnlyCut`): a kit outside the scan is not what moves.
37
+ */
38
+ async function entryOf(
39
+ steps: readonly ChainStep[],
40
+ root: string,
41
+ scanned: () => Promise<ReadonlySet<string>>,
42
+ ): Promise<Entry | undefined> {
43
+ const paths = steps.map((step) => posixRelative(root, step.path));
44
+ const own = steps.findLastIndex(
45
+ (step, index) =>
46
+ isPathUnder(root, step.path) && !hasPathSegment(paths[index] ?? '', 'node_modules'),
47
+ );
48
+ const leavesBy = steps[own + 1]?.specifier;
49
+ if (own === -1 || leavesBy === undefined) return undefined;
50
+ const cut = isDevOnlySpecifier(leavesBy)
51
+ ? devOnlyCut(steps.slice(0, own + 1), await scanned())
52
+ : undefined;
53
+ const from = cut?.index ?? own;
54
+ return {
55
+ at: paths[from] ?? '',
56
+ specifier: cut?.into ?? leavesBy,
57
+ chain: paths.slice(from),
58
+ leavesBy,
59
+ ...(cut === undefined ? {} : { cut }),
60
+ };
61
+ }
62
+
63
+ /** The finding told from `entry`: the install's fix, unless the app's import is the defect. */
64
+ function retold(found: UnresolvedImport, entry: Entry): Finding {
65
+ const { at, specifier, leavesBy, cut } = entry;
66
+ const brings = specifier === leavesBy ? '' : `, which brings in "${leavesBy}"`;
67
+ const refused = cut === undefined ? '' : ', a development entry no role may load';
68
+ const chain = [...entry.chain.map(shown), found.specifier].join(' → ');
69
+ return {
70
+ code: 'X_APP_IMPORT_UNRESOLVED',
71
+ cause: `${at} imports "${specifier}"${brings}${refused}, and that reaches ${found.missing}: ${chain}`,
72
+ fix: cut === undefined ? found.fix : devOnlyFix(at, cut, leavesBy),
73
+ at,
74
+ meta: { specifier: found.specifier, chain: [...entry.chain] },
75
+ };
76
+ }
77
+
78
+ /**
79
+ * One scan's explanations. The graph is shared: a package that would not load fails every module
80
+ * that reaches it, and each is explained over the same parsed edges.
81
+ */
82
+ export function dependencyImports(
83
+ root: string,
84
+ ): (error: unknown, file: string) => Promise<Finding> {
85
+ const base = realPath(resolve(root));
86
+ const graph = createEvaluatedGraph();
87
+ let modules: Promise<ReadonlySet<string>> | undefined;
88
+ // Globbed at most once, however many modules fail.
89
+ const scanned = (): Promise<ReadonlySet<string>> => {
90
+ modules ??= scannedModules(base);
91
+ return modules;
92
+ };
93
+ return async (error, file) => {
94
+ const found = unresolvedImport(error, root);
95
+ if (found?.referrer === undefined) return { ...findingFrom(error), at: file };
96
+ const target = realPath(found.referrer);
97
+ const walk = await graph.walk([realPath(resolve(base, file))], (edge) =>
98
+ edge.target() === target ? 'stop' : 'follow',
99
+ );
100
+ const entry = await entryOf(walk.chainTo(target), base, scanned);
101
+ if (entry !== undefined) return retold(found, entry);
102
+ // Reached through an import no source spells (`import(variable)`): the module the load was
103
+ // importing is still the one its reader can open.
104
+ return {
105
+ code: 'X_APP_IMPORT_UNRESOLVED',
106
+ cause: `importing ${file}: ${posixRelative(base, target)} imports ${found.missing}`,
107
+ fix: found.fix,
108
+ at: file,
109
+ meta: { specifier: found.specifier },
110
+ };
111
+ };
112
+ }
@@ -2,11 +2,12 @@
2
2
  // it, with `x doctor --json` as the fix, and doctor answered "shippable": the cycle closed on itself.
3
3
  // Leaf module: `output.ts` reads it for a throw outside the scan, and the scan for one inside it.
4
4
 
5
- // why: a synchronous probe for an installed package's manifest; Bun ships no path helpers.
6
- import { existsSync } from 'node:fs';
7
- import { dirname, join } from 'node:path';
8
- import { stringField } from '@ultimat3/core';
5
+ // why: a synchronous probe and read of an installed package's manifest; Bun ships no path helpers.
6
+ import { existsSync, readFileSync, realpathSync } from 'node:fs';
7
+ import { basename, dirname, join, resolve } from 'node:path';
8
+ import { isJsonObject, stringField } from '@ultimat3/core';
9
9
  import type { Finding } from './output';
10
+ import { hasPathSegment, isPathUnder } from './path-segments';
10
11
  import { posixRelative } from './posix-path';
11
12
  import { quoteArg } from './shell-quote';
12
13
 
@@ -31,32 +32,188 @@ const isInstalled = (pkg: string, referrer: string): boolean => {
31
32
  }
32
33
  };
33
34
 
35
+ /**
36
+ * Whose module it is. `installed`: under a `node_modules`, so an install is what writes it. `linked`:
37
+ * neither the app's nor installed — a checkout a link reaches, which its owner edits and installs.
38
+ */
39
+ type Place = 'app' | 'installed' | 'linked';
40
+
41
+ function placeOf(root: string, path: string): Place {
42
+ const base = realPath(resolve(root));
43
+ const real = realPath(path);
44
+ // Relative to the app, so one that itself sits under some `node_modules` is still an app.
45
+ if (hasPathSegment(posixRelative(base, real), 'node_modules')) return 'installed';
46
+ return isPathUnder(base, real) ? 'app' : 'linked';
47
+ }
48
+
49
+ /**
50
+ * `path` with its links followed, as Bun reports a referrer — or itself when they cannot be: this
51
+ * runs while a failure is being reported, over a tree an install may be rewriting.
52
+ */
53
+ export function realPath(path: string): string {
54
+ try {
55
+ return realpathSync(path);
56
+ } catch {
57
+ return path;
58
+ }
59
+ }
60
+
61
+ /** The package a module belongs to. `manifest` is absent when there is none that can be read. */
62
+ interface Owner {
63
+ readonly dir: string;
64
+ readonly manifest?: Readonly<Record<string, unknown>>;
65
+ }
66
+
67
+ /** The nearest named manifest above `file`, and never one above the package's own directory. */
68
+ function ownerOf(file: string): Owner {
69
+ for (let dir = dirname(file); ; dir = dirname(dir)) {
70
+ const manifest = readManifest(join(dir, 'package.json'));
71
+ if (manifest === 'unreadable') return { dir };
72
+ if (manifest !== 'absent' && typeof manifest['name'] === 'string') return { dir, manifest };
73
+ const above = dirname(dir);
74
+ if (above === dir || basename(above) === 'node_modules') return { dir };
75
+ }
76
+ }
77
+
78
+ /**
79
+ * Best effort by design: the caller is reporting a failed import, and a manifest an install is
80
+ * replacing — gone, half-written, a directory — must not become the failure that is reported.
81
+ */
82
+ function readManifest(path: string): Readonly<Record<string, unknown>> | 'absent' | 'unreadable' {
83
+ try {
84
+ const parsed: unknown = JSON.parse(readFileSync(path, 'utf8'));
85
+ return isJsonObject(parsed) ? parsed : 'unreadable';
86
+ } catch (error) {
87
+ return stringField(error, 'code') === 'ENOENT' ? 'absent' : 'unreadable';
88
+ }
89
+ }
90
+
91
+ /** An import that resolved to nothing, as the runtime reported it. */
92
+ export interface UnresolvedImport {
93
+ readonly specifier: string;
94
+ /** Absolute, when the runtime named it. */
95
+ readonly referrer?: string;
96
+ /** `referrer` is a package's module, installed or linked: not a file of the app's. */
97
+ readonly outside: boolean;
98
+ /** The package nobody installed; absent for a path, and for a subpath of an installed one. */
99
+ readonly pkg?: string;
100
+ /** What is missing, as a clause: `left-pad, which is not installed`. */
101
+ readonly missing: string;
102
+ readonly fix: string;
103
+ }
104
+
105
+ /** The line that shows the import to edit, in the file that holds it. */
106
+ const editFix = (specifier: string, where: string): string =>
107
+ `grep -nF -- ${quoteArg(specifier)} ${quoteArg(where)} # the import no file resolves: edit it`;
108
+
109
+ const declares = (owner: Owner, pkg: string): boolean => {
110
+ const declared = owner.manifest?.['dependencies'];
111
+ return isJsonObject(declared) && Object.hasOwn(declared, pkg);
112
+ };
113
+
114
+ /**
115
+ * The directory whose install wrote `file`, when the app's own line does not reach it: the one above
116
+ * the outermost `node_modules` on the way there. `undefined` is the app's install, in the app or in
117
+ * the workspace root above it. A directory INSIDE the app is named whichever it is: a checkout
118
+ * standing alone there has its own lockfile, and from a workspace `bun` finds the root's.
119
+ */
120
+ function foreignInstall(root: string, file: string): string | undefined {
121
+ const base = realPath(resolve(root));
122
+ const parts = posixRelative(base, realPath(file)).split('/');
123
+ const dir = resolve(base, parts.slice(0, parts.indexOf('node_modules')).join('/'));
124
+ return dir === base || isPathUnder(dir, base) ? undefined : dir;
125
+ }
126
+
127
+ /** Inside an installed package: nobody has a line to edit, and an install is what writes it. */
128
+ function installedFix(
129
+ root: string,
130
+ referrer: string,
131
+ named: string | undefined,
132
+ pkg: string | undefined,
133
+ ): string {
134
+ const owner = ownerOf(referrer);
135
+ const foreign = foreignInstall(root, referrer);
136
+ const cwd = foreign === undefined ? '' : ` --cwd ${quoteArg(foreign)}`;
137
+ if (pkg === undefined || owner.manifest === undefined) {
138
+ const why = `bun why ${String(named)}${foreign === undefined ? '' : ' there'}`;
139
+ return `bun install --force${cwd} # the installed copy lacks what it imports: reinstall it${named === undefined ? '' : `; still so: ${why}, then align the two versions`}`;
140
+ }
141
+ if (!declares(owner, pkg)) return `bun add ${quoteArg(pkg)}${cwd}`;
142
+ // A dependency the importing package DECLARES is missing from the install, not from the app's
143
+ // manifest: `bun add` would copy it into the app and leave the pruned install as it was.
144
+ return foreign === undefined
145
+ ? `bun install --frozen-lockfile # ${pkg} is a declared dependency of an installed package: restore it, and prune no declared dependency from an image`
146
+ : `bun install${cwd} # ${pkg} is a declared dependency of a package installed there: restore it`;
147
+ }
148
+
149
+ /**
150
+ * Inside a linked checkout: no install of the app's writes it, and nothing installed in the app
151
+ * resolves from it — a module resolves from its real path.
152
+ */
153
+ function linkedFix(
154
+ specifier: string,
155
+ where: string,
156
+ referrer: string,
157
+ pkg: string | undefined,
158
+ ): string {
159
+ const owner = ownerOf(realPath(referrer));
160
+ // No manifest to install from: what is left is the import itself.
161
+ if (pkg === undefined || owner.manifest === undefined) return editFix(specifier, where);
162
+ return declares(owner, pkg)
163
+ ? `bun install --cwd ${quoteArg(owner.dir)}`
164
+ : `bun add ${quoteArg(pkg)} --cwd ${quoteArg(owner.dir)}`;
165
+ }
166
+
34
167
  /**
35
168
  * Bun's `ResolveMessage`, read through `stringField`: a caught value this process did not build. The
36
169
  * `specifier` and `referrer` are the failing import's own, however many modules were importing the
37
- * file that holds it, which is what makes one finding per specifier true.
170
+ * file that holds it.
38
171
  */
39
- export function unresolvedImportFinding(error: unknown, root: string): Finding | undefined {
172
+ export function unresolvedImport(error: unknown, root: string): UnresolvedImport | undefined {
40
173
  if (stringField(error, 'code') !== 'ERR_MODULE_NOT_FOUND') return undefined;
41
174
  const specifier = stringField(error, 'specifier');
42
175
  if (specifier === undefined) return undefined;
43
176
  const referrer = stringField(error, 'referrer');
44
- const at = referrer === undefined ? undefined : posixRelative(root, referrer);
45
- const where = at ?? 'an app module';
177
+ const place = referrer === undefined ? 'app' : placeOf(root, referrer);
178
+ const where = referrer === undefined ? 'an app module' : posixRelative(root, referrer);
46
179
  const named = installablePackage(specifier);
47
180
  // Installed, and missing only the subpath: `bun add` would exit 0 and change nothing.
48
181
  const installed = named !== undefined && referrer !== undefined && isInstalled(named, referrer);
49
182
  const pkg = installed ? undefined : named;
50
- const edit = `grep -nF -- ${quoteArg(specifier)} ${quoteArg(where)} # the import no file resolves: edit it`;
183
+ const ownFix = pkg === undefined ? editFix(specifier, where) : `bun add ${quoteArg(pkg)}`;
184
+ const fixAt = (from: string): string =>
185
+ place === 'linked'
186
+ ? linkedFix(specifier, where, from, pkg)
187
+ : place === 'installed'
188
+ ? installedFix(root, from, named, pkg)
189
+ : ownFix;
51
190
  return {
52
- code: IMPORT_UNRESOLVED,
53
- cause: installed
54
- ? `${where} imports "${specifier}", and ${String(named)} is installed with no such subpath`
191
+ specifier,
192
+ ...(referrer === undefined ? {} : { referrer }),
193
+ outside: place !== 'app',
194
+ ...(pkg === undefined ? {} : { pkg }),
195
+ missing: installed
196
+ ? `"${specifier}", and ${String(named)} is installed with no such subpath`
55
197
  : pkg === undefined
56
- ? `${where} imports "${specifier}", which resolves to no file`
57
- : `an app module imports ${pkg}, which is not installed`,
58
- fix: pkg === undefined ? edit : `bun add ${quoteArg(pkg)}`,
198
+ ? `"${specifier}", which resolves to no file`
199
+ : `${pkg}, which is not installed`,
200
+ fix: referrer === undefined ? ownFix : fixAt(referrer),
201
+ };
202
+ }
203
+
204
+ /** The finding as the failing import alone tells it: at the module that holds it. */
205
+ export function unresolvedImportFinding(error: unknown, root: string): Finding | undefined {
206
+ const found = unresolvedImport(error, root);
207
+ if (found === undefined) return undefined;
208
+ const at = found.referrer === undefined ? undefined : posixRelative(root, found.referrer);
209
+ // A package the app itself imports is one `bun add`, so its cause names no importer: the render
210
+ // layer collapses findings by cause, and every importer of it is one repair.
211
+ const appsOwnPackage = !found.outside && found.pkg !== undefined;
212
+ return {
213
+ code: IMPORT_UNRESOLVED,
214
+ cause: `${appsOwnPackage ? 'an app module' : (at ?? 'an app module')} imports ${found.missing}`,
215
+ fix: found.fix,
59
216
  ...(at === undefined ? {} : { at }),
60
- meta: { specifier },
217
+ meta: { specifier: found.specifier },
61
218
  };
62
219
  }
package/src/app-load.ts CHANGED
@@ -25,7 +25,7 @@ import { setStylesheetRoot, siteAssetTable } from '@ultimat3/render/server';
25
25
  import { asyncModules } from './app-load-async';
26
26
  import { importInOrder } from './app-load-batch';
27
27
  import { isFirstPass, registeredAny, registerModule } from './app-load-register';
28
- import { unresolvedImportFinding } from './app-load-unresolved';
28
+ import { unresolvedImport, unresolvedImportFinding } from './app-load-unresolved';
29
29
  import { evictChanged, trackModule, trackStylesheets } from './app-reload-graph';
30
30
  import { API_INDEX } from './app-root';
31
31
  import { collectDeclaredCodes } from './error-contract';
@@ -239,8 +239,23 @@ export async function scannedModulePaths(root: string): Promise<readonly string[
239
239
  }
240
240
 
241
241
  /** A module that would not import, keyed by its file. */
242
- const importFinding = (error: unknown, root: string, file: string): Finding =>
243
- unresolvedImportFinding(error, root) ?? { ...findingFrom(error), at: file };
242
+ type ImportFinding = (error: unknown, file: string) => Promise<Finding>;
243
+
244
+ /**
245
+ * One per scan. An import that failed inside an installed package is explained by the app module
246
+ * that reached it (`app-load-import-chain.ts`), loaded then: a boot that imports everything never
247
+ * evaluates the walk.
248
+ */
249
+ function importFindings(root: string): ImportFinding {
250
+ let explain: Promise<ImportFinding> | undefined;
251
+ return async (error, file) => {
252
+ if (unresolvedImport(error, root)?.outside === true) {
253
+ explain ??= import('./app-load-import-chain').then((one) => one.dependencyImports(root));
254
+ return (await explain)(error, file);
255
+ }
256
+ return unresolvedImportFinding(error, root) ?? { ...findingFrom(error), at: file };
257
+ };
258
+ }
244
259
 
245
260
  /** Reads at most this many sources at once: a 12k-module app opened 12k descriptors otherwise. */
246
261
  const READ_BATCH = 64;
@@ -277,12 +292,13 @@ async function scanBatched(
277
292
  const alone = await asyncModules(root, candidates);
278
293
  const imported = await importInOrder(candidates, alone, register);
279
294
  const result: ScanResult = { files: [], findings: [] };
295
+ const importFinding = importFindings(root);
280
296
  for (const [index, absolute] of candidates.entries()) {
281
297
  const file = posixRelative(root, absolute);
282
298
  const one = imported[index];
283
299
  if (one === undefined) continue;
284
300
  if (!one.ok) {
285
- result.findings.push(importFinding(one.error, root, file));
301
+ result.findings.push(await importFinding(one.error, file));
286
302
  continue;
287
303
  }
288
304
  result.files.push(file);
@@ -299,6 +315,7 @@ async function scanSerial(
299
315
  options: ScanOptions,
300
316
  ): Promise<ScanResult> {
301
317
  const result: ScanResult = { files: [], findings: [] };
318
+ const importFinding = importFindings(root);
302
319
  for (const absolute of candidates) {
303
320
  const file = posixRelative(root, absolute);
304
321
  if (options.include !== undefined && !(await options.include(absolute))) continue;
@@ -315,7 +332,7 @@ async function scanSerial(
315
332
  try {
316
333
  module = (await import(absolute)) as Record<string, unknown>;
317
334
  } catch (error) {
318
- result.findings.push(importFinding(error, root, file));
335
+ result.findings.push(await importFinding(error, file));
319
336
  continue;
320
337
  }
321
338
  result.files.push(file);
@@ -0,0 +1,59 @@
1
+ // The specifiers no container role may evaluate, and the one edit that clears an app of one: where
2
+ // on the way from a scanned module to the import the cut is, and the line to run there. The gate's
3
+ // check (`app-dev-imports.ts`) and the load's explanation of a failed import
4
+ // (`app-load-import-chain.ts`) read one rule, so a finding at boot and one at the gate agree.
5
+
6
+ import { scannedModulePaths } from './app-load';
7
+ import { realPath } from './app-load-unresolved';
8
+ import { commentSafe } from './comment-safe';
9
+ import type { ChainStep } from './evaluated-walk';
10
+ import { quoteArg } from './shell-quote';
11
+
12
+ /**
13
+ * `@ultimat3/cli`'s barrel is every command, template and the test harness, and it imports
14
+ * `@ultimat3/testing`; a role's entry is `@ultimat3/cli/serve`. `bun:test` is the runner's own.
15
+ */
16
+ export const isDevOnlySpecifier = (specifier: string): boolean =>
17
+ specifier === '@ultimat3/cli' ||
18
+ specifier === 'bun:test' ||
19
+ /^@ultimat3\/testing(?:\/|$)/.test(specifier);
20
+
21
+ /** Every module the boot scan imports under `base`, links followed: what a cut may be made in. */
22
+ export const scannedModules = async (base: string): Promise<ReadonlySet<string>> =>
23
+ new Set((await scannedModulePaths(base)).map(realPath));
24
+
25
+ /** `apps/web/app/x.ts` → `apps/web/test/`: beside the surfaces, and outside every app-scan glob. */
26
+ const testHome = (at: string): string => {
27
+ const workspace = /^(?:apps|packages)\/[^/]+(?=\/)/.exec(at)?.[0];
28
+ return workspace === undefined ? 'a test/ directory' : `${workspace}/test/`;
29
+ };
30
+
31
+ /** Where the cut is, and the import to look for there. */
32
+ export interface DevOnlyCut {
33
+ /** Its index in the steps: the last module the boot scan imports. */
34
+ readonly index: number;
35
+ /** What that module imports on the way; `undefined` when it holds the development import itself. */
36
+ readonly into: string | undefined;
37
+ }
38
+
39
+ /**
40
+ * The cut on the way to a development import, whose holder is the last of `steps`. The holder when
41
+ * the scan imports it; when it sits outside the scan (a kit under `test/`), moving it clears nothing
42
+ * and the cut is the scanned module's edge towards it.
43
+ */
44
+ export function devOnlyCut(steps: readonly ChainStep[], scanned: ReadonlySet<string>): DevOnlyCut {
45
+ const index = Math.max(
46
+ 0,
47
+ steps.findLastIndex((step) => scanned.has(step.path)),
48
+ );
49
+ return { index, into: steps[index + 1]?.specifier };
50
+ }
51
+
52
+ /** The edit, opening with the line to look at. `at` is app-root-relative: the cut's module. */
53
+ export function devOnlyFix(at: string, cut: DevOnlyCut, specifier: string): string {
54
+ const line = `grep -nF -- ${quoteArg(cut.into ?? specifier)} ${quoteArg(at)}`;
55
+ // `commentSafe`: a workspace directory's name is the repository's, and a newline ends a comment.
56
+ return cut.into === undefined
57
+ ? `${line} # test support moves to ${commentSafe(testHome(at))}, which no role loads; a module a role needs drops this import`
58
+ : `${line} # it brings test support into a module a role loads: only a test imports that`;
59
+ }
@@ -14,6 +14,7 @@ export const CLI_BOUNDARY_ERROR_CODES = [
14
14
  'X_BOUNDARY_PACKAGE_TO_APP',
15
15
  'X_BOUNDARY_ADAPTER_IMPORT',
16
16
  'X_BOUNDARY_LOADER_IMPORT',
17
+ 'X_BOUNDARY_DEV_IMPORT',
17
18
  ] as const;
18
19
 
19
20
  export type CliBoundaryErrorCode = (typeof CLI_BOUNDARY_ERROR_CODES)[number];
@@ -29,4 +30,5 @@ export const CLI_BOUNDARY_ERROR_TITLES: Readonly<Record<CliBoundaryErrorCode, st
29
30
  X_BOUNDARY_PACKAGE_TO_APP: 'packages/ imported apps/ at runtime',
30
31
  X_BOUNDARY_ADAPTER_IMPORT: 'an app module imports an adapter installer',
31
32
  X_BOUNDARY_LOADER_IMPORT: 'an app module imports a registration loader',
33
+ X_BOUNDARY_DEV_IMPORT: 'a module a role loads imports a development entry',
32
34
  };
@@ -0,0 +1,103 @@
1
+ // What importing a set of modules EVALUATES, walked breadth first with the path to each module
2
+ // kept — so a finding about a module deep in the graph can name how it was reached. Two callers:
3
+ // the load's explanation of an import that failed inside a package (`app-load-import-chain.ts`)
4
+ // and the gate's check of what a role loads (`app-dev-imports.ts`). Never in a healthy boot.
5
+
6
+ import { importedSpecifiers, resolveImport } from './module-imports';
7
+
8
+ /** One static import, as the module at `from` spells it. `target` resolves it when it is asked. */
9
+ export interface EvaluatedImport {
10
+ readonly from: string;
11
+ readonly specifier: string;
12
+ target(): string | undefined;
13
+ }
14
+
15
+ /** `follow` walks the import's target, `skip` leaves it, `stop` ends the walk with it as the end. */
16
+ export type WalkVerdict = 'follow' | 'skip' | 'stop';
17
+
18
+ /** A module on a chain, and how the one before it spelled it — absent on the start. */
19
+ export interface ChainStep {
20
+ readonly path: string;
21
+ readonly specifier?: string;
22
+ }
23
+
24
+ export interface EvaluatedWalk {
25
+ /** Start first, `path` last: the shortest way there. Empty for a module the walk never reached. */
26
+ chainTo(path: string): readonly ChainStep[];
27
+ }
28
+
29
+ export interface EvaluatedGraph {
30
+ walk(
31
+ starts: readonly string[],
32
+ judge: (edge: EvaluatedImport) => WalkVerdict,
33
+ ): Promise<EvaluatedWalk>;
34
+ }
35
+
36
+ /** What names an import at all: a dataset or a stylesheet is a target, and never read as source. */
37
+ const CODE = /\.[cm]?[jt]sx?$/;
38
+
39
+ /** One graph, however many walks: a module is read and parsed once, whoever reaches it. */
40
+ export function createEvaluatedGraph(): EvaluatedGraph {
41
+ const edges = new Map<string, readonly EvaluatedImport[]>();
42
+
43
+ async function edgesOf(path: string): Promise<readonly EvaluatedImport[]> {
44
+ const known = edges.get(path);
45
+ if (known !== undefined) return known;
46
+ if (!CODE.test(path)) return [];
47
+ // Unreadable (a builtin, an asset Bun resolves elsewhere): no edge, as an unparseable file has.
48
+ const source = await Bun.file(path)
49
+ .text()
50
+ .catch(() => '');
51
+ const found = importedSpecifiers(path, source, 'evaluated').map(
52
+ (specifier): EvaluatedImport => {
53
+ let resolved: { readonly path: string | undefined } | undefined;
54
+ return {
55
+ from: path,
56
+ specifier,
57
+ target() {
58
+ resolved ??= { path: resolveImport(specifier, path) };
59
+ return resolved.path;
60
+ },
61
+ };
62
+ },
63
+ );
64
+ edges.set(path, found);
65
+ return found;
66
+ }
67
+
68
+ return {
69
+ async walk(starts, judge) {
70
+ const via = new Map<string, EvaluatedImport | undefined>(
71
+ starts.map((start): [string, undefined] => [start, undefined]),
72
+ );
73
+ const reached = [...via.keys()];
74
+ walking: for (const path of reached) {
75
+ for (const edge of await edgesOf(path)) {
76
+ const verdict = judge(edge);
77
+ if (verdict === 'skip') continue;
78
+ const target = edge.target();
79
+ if (target !== undefined && !via.has(target)) {
80
+ via.set(target, edge);
81
+ reached.push(target);
82
+ }
83
+ if (verdict === 'stop') break walking;
84
+ }
85
+ }
86
+ return {
87
+ chainTo(path) {
88
+ if (!via.has(path)) return [];
89
+ const chain: ChainStep[] = [];
90
+ for (let at: string | undefined = path; at !== undefined; ) {
91
+ const edge: EvaluatedImport | undefined = via.get(at);
92
+ chain.push({
93
+ path: at,
94
+ ...(edge === undefined ? {} : { specifier: edge.specifier }),
95
+ });
96
+ at = edge?.from;
97
+ }
98
+ return chain.reverse();
99
+ },
100
+ };
101
+ },
102
+ };
103
+ }
package/src/index.ts CHANGED
@@ -109,6 +109,8 @@ export type { NewShape } from './new-shapes';
109
109
  export { NEW_SHAPES } from './new-shapes';
110
110
  export type { CommandResult, Finding, JsonValue } from './output';
111
111
  export { exitCodeFor, findingFrom, render, renderFinding, renderHuman } from './output';
112
+ export type { PageRouteOptions } from './page-route';
113
+ export { pageRoute } from './page-route';
112
114
  export type { CommandSpec, FlagSpec, ParsedArgs } from './parse';
113
115
  export { flagBool, flagList, flagString, GLOBAL_FLAGS, parseArgs } from './parse';
114
116
  export type { PrerenderedPage, PrerenderReport } from './prerender';
package/src/mcp-errors.ts CHANGED
@@ -297,7 +297,7 @@ const CLI_FIXES: Readonly<Record<CliErrorCode, string>> = {
297
297
  X_BOUNDARY_PACKAGE_TO_APP:
298
298
  'x verify --only boundaries --json # after moving the shared code into the package, or importing in the opposite direction',
299
299
  X_APP_IMPORT_UNRESOLVED:
300
- 'x doctor --json # names the package to bun add, or the file whose import to edit',
300
+ 'x doctor --json # names the app module, and the install or the edit that clears it',
301
301
  X_STREAM_ALREADY_FLUSHED:
302
302
  'load: async () => { setCookie(name, value); return data; }, // in defineRoute, never inside a Hole',
303
303
  X_QUERY_SLICE_ENTITY:
@@ -393,6 +393,8 @@ const CLI_FIXES: Readonly<Record<CliErrorCode, string>> = {
393
393
  // raised error's own `fix:` carries the named invocation; `ULTIMATE_TASK_RUN` stays in the cause.
394
394
  X_TASK_RUN_PRODUCTION:
395
395
  'x tasks list --json # then name the task: x tasks run <name> --production --json',
396
+ X_BOUNDARY_DEV_IMPORT:
397
+ 'x verify --only boundaries --json # names the module and its import: move test support to apps/web/test/, which no role loads, or drop the import from a module a role needs',
396
398
  };
397
399
 
398
400
  const isCliCode = (code: string): code is CliErrorCode =>
@@ -20,28 +20,39 @@ const transpilers = {
20
20
  tsx: new Bun.Transpiler({ loader: 'tsx' }),
21
21
  };
22
22
 
23
- /**
24
- * Absolute paths, in source order. A file that will not parse imports nothing yet, and a
25
- * specifier that will not resolve contributes no edge: the module's own import reports both.
26
- */
27
- export function resolvedImports(path: string, source: string, edges: ImportEdges): string[] {
23
+ /** Every specifier `source` names, as written and in source order. Unparseable: it names none yet. */
24
+ export function importedSpecifiers(
25
+ path: string,
26
+ source: string,
27
+ edges: ImportEdges,
28
+ ): readonly string[] {
28
29
  const transpiler = path.endsWith('x') ? transpilers.tsx : transpilers.ts;
29
- let specifiers: readonly { readonly path: string; readonly kind: string }[];
30
30
  try {
31
- specifiers =
31
+ const imports =
32
32
  edges === 'referenced'
33
33
  ? transpiler.scanImports(source)
34
34
  : transpiler.scan(source).imports.filter((one) => one.kind !== 'dynamic-import');
35
+ return imports.map((one) => one.path);
35
36
  } catch {
36
37
  return [];
37
38
  }
38
- const found: string[] = [];
39
- for (const { path: specifier } of specifiers) {
40
- try {
41
- found.push(Bun.resolveSync(specifier, dirname(path)));
42
- } catch {
43
- // Unresolvable: no edge.
44
- }
39
+ }
40
+
41
+ /** The file `specifier` is from `path`, as Bun resolves it — `undefined` when it resolves to none. */
42
+ export function resolveImport(specifier: string, path: string): string | undefined {
43
+ try {
44
+ return Bun.resolveSync(specifier, dirname(path));
45
+ } catch {
46
+ return undefined;
45
47
  }
46
- return found;
48
+ }
49
+
50
+ /**
51
+ * Absolute paths, in source order. A file that will not parse imports nothing yet, and a
52
+ * specifier that will not resolve contributes no edge: the module's own import reports both.
53
+ */
54
+ export function resolvedImports(path: string, source: string, edges: ImportEdges): string[] {
55
+ return importedSpecifiers(path, source, edges).flatMap(
56
+ (specifier) => resolveImport(specifier, path) ?? [],
57
+ );
47
58
  }
@@ -0,0 +1,75 @@
1
+ // Single responsibility: a registered page's GET through the real `httpPipeline`, for a unit test —
2
+ // what a visitor RECEIVES (status, headers, cookies set, redirect, document), where `renderRoute`
3
+ // answers what the page renders. It lives in cli because the page handler (`appRoutes`) does.
4
+
5
+ import { assert } from '@ultimat3/core';
6
+ import { defineHttpConfig, httpPipeline, httpRouter } from '@ultimat3/http';
7
+ import { attachedIsr } from './runtime-isr';
8
+ import { appRoutes } from './runtime-render';
9
+
10
+ export interface PageRouteOptions {
11
+ /** Request headers, as a browser sends them (`accept-language`, `if-none-match` …). */
12
+ readonly headers?: Readonly<Record<string, string>>;
13
+ /**
14
+ * Cookies the request carries, by name; each value is percent-encoded as `useRequestCookie`
15
+ * decodes it. Pass either this or a `cookie` header, never both.
16
+ */
17
+ readonly cookies?: Readonly<Record<string, string>>;
18
+ /** The build the document names. Default `'page-route'`. */
19
+ readonly buildId?: string;
20
+ }
21
+
22
+ const ORIGIN = 'http://localhost';
23
+
24
+ const cookieHeader = (cookies: Readonly<Record<string, string>>): string =>
25
+ Object.entries(cookies)
26
+ .map(([name, value]) => `${name}=${encodeURIComponent(value)}`)
27
+ .join('; ');
28
+
29
+ /**
30
+ * `GET <path>` against the pages registered in this process (`registerRoute`, or `loadApp`), as the
31
+ * response a visitor gets. `path` is the URL path and query (`/es/precios?page=2`), starting with
32
+ * `/`. A path no page claims answers the pipeline's own 404.
33
+ *
34
+ * ```ts
35
+ * const response = await pageRoute('/dashboard', { cookies: { sid: 's-1' } });
36
+ * expect(response.status).toBe(200);
37
+ * expect(response.headers.getSetCookie()).toEqual([]);
38
+ * ```
39
+ */
40
+ export async function pageRoute(path: string, options: PageRouteOptions = {}): Promise<Response> {
41
+ assert(
42
+ path.startsWith('/'),
43
+ 'pageRoute requires a URL path starting with a slash',
44
+ "pageRoute('/dashboard?tab=2')",
45
+ );
46
+ const headers = new Headers(options.headers);
47
+ if (options.cookies !== undefined) {
48
+ assert(
49
+ !headers.has('cookie'),
50
+ 'pageRoute was handed both `cookies` and a `cookie` header',
51
+ "pageRoute('/dashboard', { cookies: { sid: 's-1' } })",
52
+ );
53
+ if (Object.keys(options.cookies).length > 0) {
54
+ headers.set('cookie', cookieHeader(options.cookies));
55
+ }
56
+ }
57
+ const buildId = options.buildId ?? 'page-route';
58
+ // One ISR controller per call, released after it: `appRoutes` would otherwise attach one it
59
+ // never detaches, and every call of a suite would leave a revalidator behind.
60
+ const { isr, release } = attachedIsr({ buildId });
61
+ try {
62
+ const pipeline = httpPipeline({
63
+ table: httpRouter(appRoutes({ buildId, isr })),
64
+ config: defineHttpConfig({
65
+ dev: false,
66
+ buildId,
67
+ hostname: '127.0.0.1',
68
+ rateLimit: { scope: 'process' },
69
+ }),
70
+ });
71
+ return await pipeline.handle(new Request(`${ORIGIN}${path}`, { headers }), { role: 'web' });
72
+ } finally {
73
+ release();
74
+ }
75
+ }
@@ -0,0 +1,145 @@
1
+ // Every way the boot scan has into each module holding a development import: the holder itself when
2
+ // it is scanned, else one chain per scanned edge towards it through modules outside the scan. One
3
+ // pass backwards from all the holders at once, each module read once per distance it is reached at
4
+ // and not once per holder: helpers that reconverge carry every holder below them together.
5
+
6
+ import type { ChainStep, EvaluatedImport } from './evaluated-walk';
7
+
8
+ /** A set of holders, one bit each: what reached a module together is moved and compared at once. */
9
+ type Holders = bigint;
10
+
11
+ /** The holders below a module, by how many imports below it they are. */
12
+ type Below = ReadonlyMap<number, Holders>;
13
+
14
+ /** One import of a module's, and the holders it is the first step of the shortest way to. */
15
+ interface Hop {
16
+ readonly edge: EvaluatedImport;
17
+ readonly target: string;
18
+ readonly holders: Holders;
19
+ }
20
+
21
+ /** `edges` by `key`, in the order given: a module's own stay in the order it writes them. */
22
+ function indexed(
23
+ edges: readonly EvaluatedImport[],
24
+ key: (edge: EvaluatedImport) => string | undefined,
25
+ ): ReadonlyMap<string | undefined, readonly EvaluatedImport[]> {
26
+ const index = new Map<string | undefined, EvaluatedImport[]>();
27
+ for (const edge of edges) {
28
+ const known = index.get(key(edge)) ?? [];
29
+ known.push(edge);
30
+ index.set(key(edge), known);
31
+ }
32
+ return index;
33
+ }
34
+
35
+ const together = (below: Below | undefined): Holders =>
36
+ [...(below?.values() ?? [])].reduce((all, holders) => all | holders, 0n);
37
+
38
+ /** Which bits are set, read off the digits: the clear ones between them cost no step each. */
39
+ function bitsOf(holders: Holders): readonly number[] {
40
+ const digits = holders.toString(2);
41
+ const found: number[] = [];
42
+ for (let at = digits.indexOf('1'); at !== -1; at = digits.indexOf('1', at + 1)) {
43
+ found.push(digits.length - 1 - at);
44
+ }
45
+ return found;
46
+ }
47
+
48
+ /** How far below each module outside the scan every holder is, shortest way. */
49
+ function distances(
50
+ bits: ReadonlyMap<string, Holders>,
51
+ scanned: ReadonlySet<string>,
52
+ into: ReadonlyMap<string | undefined, readonly EvaluatedImport[]>,
53
+ ): ReadonlyMap<string, Below> {
54
+ const below = new Map<string, Map<number, Holders>>();
55
+ const reached = new Map(bits);
56
+ let frontier: ReadonlyMap<string, Holders> = bits;
57
+ for (let distance = 0; frontier.size > 0; distance += 1) {
58
+ const next = new Map<string, Holders>();
59
+ for (const [path, holders] of frontier) {
60
+ const known = below.get(path) ?? new Map<number, Holders>();
61
+ below.set(path, known.set(distance, holders));
62
+ for (const { from } of into.get(path) ?? []) {
63
+ if (scanned.has(from)) continue;
64
+ const had = reached.get(from) ?? 0n;
65
+ const fresh = holders & ~had;
66
+ if (fresh === 0n) continue;
67
+ reached.set(from, had | fresh);
68
+ next.set(from, (next.get(from) ?? 0n) | fresh);
69
+ }
70
+ }
71
+ frontier = next;
72
+ }
73
+ return below;
74
+ }
75
+
76
+ /**
77
+ * The ways into each of `holders` over the app's followed `edges`. Shortest, and of two as short the
78
+ * one the module higher up imports first. Never through a scanned module: its own edge is the cut.
79
+ */
80
+ export function scanWays(
81
+ holders: readonly string[],
82
+ scanned: ReadonlySet<string>,
83
+ edges: readonly EvaluatedImport[],
84
+ ): (holder: string) => readonly (readonly ChainStep[])[] {
85
+ const outside = [...new Set(holders)].filter((holder) => !scanned.has(holder));
86
+ const bits = new Map(
87
+ outside.map((holder, index): [string, Holders] => [holder, 1n << BigInt(index)]),
88
+ );
89
+ const into = indexed(edges, (edge) => edge.target());
90
+ const below = distances(bits, scanned, into);
91
+ const onward = indexed(edges, (edge) => edge.from);
92
+ const hops = new Map<string, readonly Hop[]>();
93
+
94
+ /** Told once per module, whichever chains pass through it. */
95
+ function hopsOf(path: string): readonly Hop[] {
96
+ const known = hops.get(path);
97
+ if (known !== undefined) return known;
98
+ const here = below.get(path);
99
+ let left = together(here);
100
+ const found: Hop[] = [];
101
+ for (const edge of onward.get(path) ?? []) {
102
+ if (left === 0n) break;
103
+ const target = edge.target();
104
+ if (target === undefined) continue;
105
+ const closer = below.get(target);
106
+ let nearer = 0n;
107
+ for (const [distance, at] of here ?? []) nearer |= at & (closer?.get(distance - 1) ?? 0n);
108
+ // A holder an earlier import already leads to is that one's.
109
+ if ((nearer & left) === 0n) continue;
110
+ left &= ~nearer;
111
+ found.push({ edge, target, holders: nearer });
112
+ }
113
+ hops.set(path, found);
114
+ return found;
115
+ }
116
+
117
+ /** From a module the holder is below, down to it: the steps after the module itself. */
118
+ function down(from: string, bit: Holders): readonly ChainStep[] {
119
+ const steps: ChainStep[] = [];
120
+ const hopAt = (path: string): Hop | undefined =>
121
+ hopsOf(path).find((hop) => (hop.holders & bit) !== 0n);
122
+ for (let hop = hopAt(from); hop !== undefined; hop = hopAt(hop.target)) {
123
+ steps.push({ path: hop.target, specifier: hop.edge.specifier });
124
+ }
125
+ return steps;
126
+ }
127
+
128
+ /** The scanned edges into the modules each holder is below, in the order given. */
129
+ const cuts = new Map(outside.map((holder): [string, Hop[]] => [holder, []]));
130
+ for (const edge of edges) {
131
+ const target = (scanned.has(edge.from) ? edge.target() : undefined) ?? '';
132
+ const holders = together(below.get(target));
133
+ for (const bit of bitsOf(holders))
134
+ cuts.get(outside[bit] ?? '')?.push({ edge, target, holders });
135
+ }
136
+
137
+ return (holder) =>
138
+ scanned.has(holder)
139
+ ? [[{ path: holder }]]
140
+ : (cuts.get(holder) ?? []).map(({ edge, target }) => [
141
+ { path: edge.from },
142
+ { path: target, specifier: edge.specifier },
143
+ ...down(target, bits.get(holder) ?? 0n),
144
+ ]);
145
+ }
@@ -10,6 +10,7 @@ import type { MetaIssue } from '@ultimat3/seo';
10
10
  import { llmsDescriptionIssues, validateMeta } from '@ultimat3/seo';
11
11
  import { checkAgentsMd } from './app-agents-md';
12
12
  import { readAppSources } from './app-boundaries';
13
+ import { devImportWarnings } from './app-dev-imports';
13
14
  import { envExampleFindings } from './app-env';
14
15
  import { loadApp } from './app-load';
15
16
  import { appManifest } from './app-manifest';
@@ -125,18 +126,21 @@ export const VERIFY_STEPS: readonly VerifyStep[] = [
125
126
  // second time (`guard-sources.ts`).
126
127
  //
127
128
  // A report-only guard's findings ride as warnings, as the filesize band does: listed, never red.
129
+ // So does a development entry a role loads (`app-dev-imports.ts`).
128
130
  async run(ctx) {
129
131
  const sources = await readAppSources(ctx.root);
130
132
  const guards = await guardReport(ctx.root, sources);
133
+ const warnings = [
134
+ ...guards.warnings.map(guardWarningLine),
135
+ ...(await devImportWarnings(ctx.root)),
136
+ ];
131
137
  return {
132
138
  ...fromFindings([
133
139
  ...(await appBoundaryFindings(ctx.root, sources)),
134
140
  ...guards.findings,
135
141
  ...(await hostFindings(ctx, 'boundaries')),
136
142
  ]),
137
- ...(guards.warnings.length === 0
138
- ? {}
139
- : { warnings: guards.warnings.map(guardWarningLine) }),
143
+ ...(warnings.length === 0 ? {} : { warnings }),
140
144
  };
141
145
  },
142
146
  },
package/wiki/Auth.md CHANGED
@@ -227,7 +227,7 @@ const approved = await verifyPasskeyEvidence(evidence, { rpId: 'example.com', or
227
227
  |---|---|
228
228
  | TOTP + recovery codes | `enrolTotp`, `saveTotpSecret`, `generateRecoveryCodes`. The secret is **sealed at rest** under the app's master key and a plaintext one is refused, never read (`X_MFA_SECRET_UNSEALED`; `x auth seal-mfa` seals rows from before); a recovery code is consumed in one statement, so it works once. A password proven with a factor outstanding is `X_MFA_REQUIRED`, whose `meta.challenge` is a sealed five-minute credential; `completeMfa(auth, challenge, code)` finishes the sign-in, meters the guess against the same lockout buckets a password guess spends, and refuses a spent code on every replica (`x_totp_steps`, installed by the boot) |
229
229
  | email verification, password reset, any other mailed credential | `defineVerificationPurpose({ name, template, ttlMs, identifier? })` → `{ issue, consume }` (`As of 2026-11`); `emailVerification` and `passwordReset` are its two built-in instances, and `issueVerification` / `consumeVerification` take any declared name. A token is consumed only when its hash matches, so a wrong guess cannot burn the victim's live link, and one purpose's token never consumes another's. A name declared twice or with no template is `X_VERIFICATION_PURPOSE_INVALID` at boot; an undeclared one at the call is `X_VERIFICATION_PURPOSE_UNKNOWN` (400). `VerificationPurpose` is `string`: a `switch` over it needs a default arm. The mail is sent through an injected `MailSender` ([Mail](Mail)) |
230
- | sign-in by mailed link | Not exported yet: `signInWithLink` stays internal to `@ultimat3/auth` and ships in the next minor (`As of 2026-11`). A mailed credential today is `defineVerificationPurpose` + `consumeVerification` |
230
+ | sign-in by mailed link | `signInWithLink(auth, { purpose, identifier, token, signUp? })` (`As of 2026-11`): consumes a link issued under a purpose declared `signIn: true` (`defineVerificationPurpose`) and answers what `login()` answers. TOTP enrolled: `X_MFA_REQUIRED` with the sealed challenge and no session, finished by `completeMfa`. The link is spent first, so it is good for one attempt; a wrong token leaves it live. No account: refused, or created verified and passwordless when the call declares `signUp`. A disabled account, and one that never verified its address, are refused. Recovery requires an app-owned flow that proves the inbox, clears all credentials while disabled and atomically checks ownership before reopening, coordinated with every administrative disable. `updateUser` and `enableUser` do not supply that check. `'email-verify'`, `'password-reset'` and any declared purpose not marked `signIn: true` are not sign-in purposes (`X_CONFIG_INVALID`); an undeclared name is `X_VERIFICATION_PURPOSE_UNKNOWN` |
231
231
  | API keys — how an agent authenticates | `issueApiKey` → `ult_<env>_<id>_<secret>`, shown once; `verifyApiKey` + `apiKeyActor` give a `kind: 'agent'` actor whose scopes are the key's and never the owner's roles (`X_API_KEY_INVALID`). A key is its owner's credential: a missing or disabled owner refuses it on the next use, a wildcard scope (`*`, `<resource>:*`) is refused at issue, and an owned key keeps only the scopes its owner's grants cover — pass `grantsOf` to expand roles ([`packages/auth/README.md`](https://github.com/developerz-ai/ultimate/blob/main/packages/auth/README.md)); a key with no `userId` is unchanged. `apiKeyResolver(() => store)` is both as the `resolveToken` a bearer mount and `defineAppMcp()` take: `{ actor, scopes }` for a live key, one `null` for every wrong one, and a store fault left a throw. In a test the store is `memoryAuthAdapter()` |
232
232
  | service-to-service | `verifyWorkloadToken` reads a Kubernetes service-account token, a SPIFFE JWT-SVID or a cloud IMDS token (they are all one JWT); `actorFromService` gives a `kind: 'service'` actor. The returned `WorkloadToken` carries `raw`, the whole decoded payload, read only after every check held. mTLS is the mesh's job |
233
233
  | an external issuer's bearer (`As of 2026-11`) | `jwtBearerResolver({ keys, issuers, audience, requiredScope?, accept?, actorOf })` — `apiKeyResolver`'s twin for JWTs, the `resolveToken` a bearer mount and `defineAppMcp()` take. `keys` is a thunk read when a token arrives (no discovery at import); `accept(raw)` is the app's own claim check after the signature; `actorOf(token)` builds the actor. Every refusal — signature, issuer, audience, expiry, scope, `accept`, and a key set that cannot be read — is `null` plus one `auth.jwt_bearer.refused` log line naming the check, never a claim's value. The mount answers that `null` as `401 X_UNAUTHENTICATED` |
package/wiki/Testing.md CHANGED
@@ -53,6 +53,8 @@ export function useMigratedDatabase(): void {
53
53
  }
54
54
  ```
55
55
 
56
+ **Shared test support lives in `apps/<app>/test/`** (a package's in `packages/<pkg>/test/`), never under `site/`, `app/`, `api/` or `shared/`. The boot scan imports the modules there, all but tests, client islands (`*.island.tsx`) and their `*.island.states.ts`, so a helper named `board.fixture.ts` beside its tests is evaluated by a role, `@ultimat3/cli` and `@ultimat3/testing` with it. Tests alone import what is in `test/`. The `boundaries` step warns `X_BOUNDARY_DEV_IMPORT`, naming the import to cut and the chain.
57
+
56
58
  | Scope | What it gets |
57
59
  |---|---|
58
60
  | a test **file** | the worker's database with its DATA reset to the template's — every table truncated and re-filled, every sequence reset, triggers off meanwhile (`reusableDatabase`) |
@@ -487,6 +489,29 @@ opened: standalone that is the default locale, inside your own `runWithContext`
487
489
  the actor still acts and the locale still holds. `renderView` refuses
488
490
  a component that renders an `island()` — its hydration timing is a route's. `As of 2026-10`.
489
491
 
492
+ ### A page's own GET
493
+
494
+ `renderRoute` says what a page renders. To see what a visitor RECEIVES (status, headers, cookies
495
+ set, a redirect, the document) through the real pipeline, import `pageRoute` from `@ultimat3/cli`,
496
+ the package that owns the page handler:
497
+
498
+ ```ts
499
+ import { pageRoute } from '@ultimat3/cli';
500
+ import { expect, unitTest } from '@ultimat3/testing';
501
+
502
+ unitTest('the dashboard refuses an anonymous visitor', async () => {
503
+ expect((await pageRoute('/dashboard')).status).toBe(401);
504
+ const seen = await pageRoute('/dashboard', { cookies: { sid: 's-1' } });
505
+ expect(seen.status).toBe(200);
506
+ });
507
+ ```
508
+
509
+ `pageRoute(path, { headers?, cookies?, buildId? }): Promise<Response>` sends `GET <path>` (URL path
510
+ and query, starting with `/`) through `httpPipeline` over the pages registered in the process
511
+ (`registerRoute`, or `loadApp`). `cookies` are percent-encoded as `useRequestCookie` decodes them;
512
+ give `cookies` or a `cookie` header, not both. A path no page claims is the pipeline's 404; a path
513
+ without a leading `/` is `X_INVARIANT`, naming the fix. `As of 2026-11`.
514
+
490
515
  ## Asserting on what an element carries
491
516
 
492
517
  A string cannot say whether a node carries `aria-live`, or what its `onKeyDown` does. Walk the tree
@@ -37,7 +37,7 @@ The `--json` form is the same content as the terminal form. Paste the JSON into
37
37
  | `X_DB_DRIFT` | schema differs from migrations (a column added by hand, or a generated migration never applied) | `x db gen "<message>"` then `x db migrate`. A column no entity declares is an empty diff: declare it, or restore the migration and `x db reset` |
38
38
  | `X_DB_DRIFT`, cause *the dump holds a column no migration's snapshot records* | an applied migration was edited, and `x db gen` wrote the edit into `packages/db/schema/` | `git checkout -- packages/db/migrations packages/db/schema`. Meant it: declare the column on its entity, then `x db gen "<change>"` |
39
39
  | `X_MIGRATION_CONFLICT`, *was applied with checksum* | an applied migration's file was edited | `git log -- packages/db/migrations/<id>.sql`, then `git checkout <rev> -- …` the revision whose checksum the ledger names, then `x db gen "<change>"`. `x db gen` first exits 0 and poisons the dump |
40
- | `X_APP_IMPORT_UNRESOLVED` | an app module imports a package nobody installed, or a path with no file behind it. One finding per specifier | `bun add <pkg>`, or edit the import in the file the finding names. `x doctor` reports it too |
40
+ | `X_APP_IMPORT_UNRESOLVED` | an app module imports a package nobody installed, or a path with no file behind it. A package the app imports is one finding, however many modules import it. A failure inside an installed package is one finding per app module to edit, with the chain when static imports spell it | `bun add <pkg>`, or edit the import in the file the finding names. A pruned dependency: `bun install --frozen-lockfile`; a damaged package: `bun install --force`. `x doctor` reports it too |
41
41
  | `X_DB_DRIFT` on a brand-new app, cause *packages/db has a schema but no migration recorded it* | expected: `x new` writes no migration, and `x db gen` is the only writer of `packages/db/migrations`. Only an app that declares an entity reports it — zero declared against zero recorded is agreement | `x db gen "initial"` then `x db migrate` — `bun run setup` does both |
42
42
  | `X_DB_DRIFT` after deleting the last entity, migrations still committed | correct, and not the case above: the migrations record tables the source no longer declares | `x db gen "drop <table>"` → it refuses with `X_MIGRATION_IRREVERSIBLE` → re-run as `x db gen "drop <table>" --allow-destructive`, or put the entity back |
43
43
  | `X_MIGRATION_FORKED` after merging two branches | each ran `x db gen` from one parent, so the newest `.snapshot.json` omits the other's work | `x db gen --merge-fork`: no SQL changes, nothing is deleted. Do not generate a `record …` migration. If the cause says a migration creates something *again*, follow its `x db status --json` check, and never delete a migration a database applied |
package/wiki/Upgrading.md CHANGED
@@ -357,6 +357,7 @@ A setter still on a package's `.` barrel is `X_ADAPTER_PORT_INCOMPLETE` on the `
357
357
  | fix text changed, codes unchanged (**31.49.0**): `X_ENV_MISSING` is the line to add to the file the environment loads; `X_CATALOG_MISSING_KEYS`'s comment half; `X_TEST_FAILED` reruns the first failing file; on the embedded development database `X_MIGRATION_CONFLICT` and `X_MIGRATION_ROLLBACK_DESTRUCTIVE` lead with `x stop --json && x db reset` | anything matching those strings exactly: `grep -rn 'x env check\|as ⟦key⟧' <your scripts>` and match the new text |
358
358
  | new scaffolds (**31.49.0**): `docker/docker-compose.test.yml` is named `<app>-test-<hash of the directory>` with ports picked per directory, and `package.json` declares `@ultimat3/realtime` | nothing; an existing app keeps its `name:` and dependency set. One importing `@ultimat3/realtime` without declaring it: `bun add --exact @ultimat3/realtime@$(bun -p "require('./package.json').dependencies['@ultimat3/core']")`. Sharing a test stack with a same-named app: its own `name:` and ports in the compose file and `docker/test-services.env` |
359
359
  | a production container runs one process per declared CPU (**31.49.0**, `ULTIMATE_PROCESSES=auto`, [Processes per container](Deployment#processes-per-container)), and `jobs.concurrency`, `jobs.maxInFlight` and `DATABASE_POOL_MAX` are per **container**, split across its processes. A no-op for a container that declares no CPU quota (no `cpus:` in Compose, no CPU limit in Kubernetes — every scaffold before this): it still runs one process, where container and process are the same. A service that **already** declares `cpus:` of 2 or more, or a Kubernetes CPU limit of 2 or more, runs that many processes once every clamp passes (shared state, the pool, a prebuilt image). The new scaffold's compose declares `cpus:` per role and `init: true`, and carries `sysctls: { net.ipv4.tcp_migrate_req: 1 }` on `web`/`sync` commented out (Linux ≥ 5.14 only: on an older kernel Docker refuses to create the container); its chart pins `ULTIMATE_PROCESSES: "1"` | with no CPU quota anywhere: nothing. A service with `cpus:` or a CPU limit ≥ 2: `x doctor` names the count each role would run; set `ULTIMATE_PROCESSES=1` on it to keep one process, or keep N and, on a host ≥ Linux 5.14, add `sysctls: { net.ipv4.tcp_migrate_req: 1 }` to `web`/`sync`. To use a second core on purpose: `cpus: '2'` on the service (and 256 MiB of `mem_limit` per process), `init: true`, the same `sysctls:` line where the kernel has it, then `x doctor`. A worker with `concurrency: 1` stays serial across the container |
360
+ | `x verify`'s `boundaries` step lists `X_BOUNDARY_DEV_IMPORT` under `warnings` for each import to cut where a module the boot scan imports reaches `@ultimat3/cli` (the barrel), `@ultimat3/testing` or `bun:test` through static imports of the app's own files (**31.51.0**). The step stays green; a refusal is planned for `next`. `X_APP_IMPORT_UNRESOLVED` for an import that failed inside an installed package is now `at` the app module that reached it, with `meta.chain` when static imports spell the way there | `git mv apps/web/app/<slice>/<name>.fixture.ts apps/web/test/` and repoint its tests, or drop the import from a module a role needs |
360
361
 
361
362
  ## 29.x → 30.0.0, entry by entry
362
363