@ultimat3/cli 31.0.0 → 31.1.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.
@@ -0,0 +1,189 @@
1
+ // One route photographed: boot (or find) the server, drive the page, settle the islands, take the
2
+ // picture and write `shot.png` beside the `verdict.json` that gates. The driver and the boot are
3
+ // arguments, so `bun test` proves the whole capture with no Chrome.
4
+
5
+ import { mkdirSync } from 'node:fs'; // why: Bun has no recursive directory create.
6
+ import { join } from 'node:path'; // why: Bun exposes no path-join primitive.
7
+ import { systemClock } from '@ultimat3/core/adapter';
8
+ import type { ShotColorScheme, ShotDriver, ShotPage, ShotSession } from './browser-launcher-port';
9
+ import { type ShotCookiePair, shotCookies } from './shot-cookie';
10
+ import { readShotGpu } from './shot-gpu';
11
+ import { acceptLanguageHeaders } from './shot-locale';
12
+ import type { ShotServer } from './shot-server';
13
+ import { allowHostsFrom } from './shot-server';
14
+ import { SETTLE_POLL_MS, settleIslands } from './shot-settle';
15
+ import { themeChoiceExpression } from './shot-theme';
16
+ import type { IslandCount, ShotArtifacts } from './shot-verdict';
17
+ import {
18
+ buildVerdict,
19
+ documentStatus,
20
+ ISLAND_PROBE,
21
+ parseIslandProbe,
22
+ verdictJson,
23
+ } from './shot-verdict';
24
+
25
+ export const SHOT_IMAGE = 'shot.png';
26
+ export const SHOT_VERDICT = 'verdict.json';
27
+
28
+ export interface ShotRun {
29
+ readonly route: string;
30
+ readonly outDir: string;
31
+ readonly driver: ShotDriver;
32
+ readonly boot: () => Promise<ShotServer>;
33
+ readonly settleMs: number;
34
+ readonly timeoutMs: number;
35
+ readonly fullPage: boolean;
36
+ /**
37
+ * `--allow-hosts`, verbatim. The app's own host is added once the server is up and never here:
38
+ * with `--port 0` the port — and therefore the origin — does not exist until after the boot.
39
+ */
40
+ readonly extraHosts?: string | undefined;
41
+ /**
42
+ * The theme the picture is of. Two things happen BEFORE navigation, because the boot script runs
43
+ * inline and nothing after `goto` can reach it: `prefers-color-scheme` is emulated so the boot's
44
+ * "system" branch answers the same on every box, AND the scheme is stored as the visitor's
45
+ * choice under `THEME_STORAGE_KEY` (`shot-theme.ts`), because an app with `theme.defaultMode`
46
+ * set answers that before the OS and only a stored choice beats it (issue #489). Absent means
47
+ * neither: the box's own preference and the app's own default — what `x shot` has always done,
48
+ * and the point of `defaultMode` — and `ui.shot` names one explicitly for exactly that reason.
49
+ */
50
+ readonly colorScheme?: ShotColorScheme | undefined;
51
+ /** CSS pixels the page is laid out in; absent is the driver's default. */
52
+ readonly viewport?: { readonly width: number; readonly height: number } | undefined;
53
+ /**
54
+ * Sent as `Accept-Language` on every request. The command always sets it — `--locale`, or the
55
+ * app's default locale — so a picture never depends on the language of the machine's Chrome.
56
+ */
57
+ readonly acceptLanguage?: string | undefined;
58
+ /**
59
+ * `--cookie`: set before the first navigation, each for the server's own URL once it is up —
60
+ * so a consent banner (or any cookie-held choice) is decided in the picture.
61
+ */
62
+ readonly cookies?: readonly ShotCookiePair[] | undefined;
63
+ readonly now?: (() => Date) | undefined;
64
+ /**
65
+ * `--expect-status`: the document status this shot is ok with — `404` to photograph the not-found
66
+ * page on purpose. Absent means any 2xx, and anything else fails the verdict with the status.
67
+ */
68
+ readonly expectStatus?: number | undefined;
69
+ /**
70
+ * Something to do with the page AFTER the islands settled and BEFORE the picture — `ui.inspect`
71
+ * reads the DOM here, on the one navigation the picture already paid for. `settle` re-runs the
72
+ * island poll (an action that mounts something changes the count the verdict reports); the
73
+ * caller who never calls it gets the count from the first settle.
74
+ */
75
+ readonly act?:
76
+ | ((page: ShotPage, settle: () => Promise<IslandCount | null>) => Promise<void>)
77
+ | undefined;
78
+ /**
79
+ * The clock the settle window runs on — the same seam `SettleOptions.sleep` and
80
+ * `InteractDeps.sleep` take, and the reason they had none on this path: `settleMs` was a
81
+ * `Bun.sleep` here, so a caller that injected a sleep everywhere else still paid the real
82
+ * 2000 ms window in wall time once per `runShot`, and a test doing it twice raced its own
83
+ * per-test timeout on a slower box. Absent is `Bun.sleep`: production waits for real.
84
+ */
85
+ readonly sleep?: ((ms: number) => Promise<void>) | undefined;
86
+ }
87
+
88
+ /** Nothing here may replace the failure that caused it, so a teardown throw is swallowed. */
89
+ const quietly = async (stop: () => Promise<void>): Promise<void> => {
90
+ await stop().catch(() => undefined);
91
+ };
92
+
93
+ /**
94
+ * Boot (or find) the server, photograph one route, write both artifacts. The driver and the boot
95
+ * are ARGUMENTS: `bun test` drives this with `fakeBrowser()` and a stub server, so the whole
96
+ * command is proved on a machine with no Chrome — which this command is explicitly excluded from
97
+ * the gate for needing.
98
+ */
99
+ export async function runShot(options: ShotRun): Promise<ShotArtifacts> {
100
+ const server = await options.boot();
101
+ const sleep = options.sleep ?? ((ms: number): Promise<void> => Bun.sleep(ms));
102
+ let session: ShotSession | undefined;
103
+ try {
104
+ const requestedUrl = new URL(options.route, server.url).toString();
105
+ session = await options.driver.open({
106
+ name: 'x shot',
107
+ // The host the picture is of, plus whatever the caller named. Never `*`: a headless browser
108
+ // inside your network is the widest SSRF surface an app can own, and a screenshot command is
109
+ // not the place to open it by default. Every refusal lands in the verdict's `refused` count.
110
+ rules: { allowHosts: allowHostsFrom(server.url, options.extraHosts) },
111
+ clock: systemClock,
112
+ timeoutMs: options.timeoutMs,
113
+ ...(options.viewport === undefined ? {} : { viewport: options.viewport }),
114
+ ...(options.acceptLanguage === undefined
115
+ ? {}
116
+ : { headers: acceptLanguageHeaders(options.acceptLanguage) }),
117
+ ...(options.cookies === undefined || options.cookies.length === 0
118
+ ? {}
119
+ : { cookies: shotCookies(options.cookies, new URL(server.url).toString()) }),
120
+ });
121
+ const page = session.page;
122
+ if (options.colorScheme !== undefined) {
123
+ await page.colorScheme(options.colorScheme);
124
+ const choice = themeChoiceExpression(options.colorScheme);
125
+ if (choice !== undefined) await page.prepare(choice);
126
+ }
127
+ await page.goto(requestedUrl, { timeout: options.timeoutMs });
128
+ // Read NOW as well as at capture: the network ring is bounded, and a page that fires a few
129
+ // hundred requests while it settles evicts the document entry the verdict needs.
130
+ const landedStatus = documentStatus(page.network(), page.url());
131
+ if (options.settleMs > 0) await sleep(options.settleMs);
132
+ // A probe may answer nothing (a page refusing evaluation, a driver with no JS engine): `null`
133
+ // says so, where a `0` would claim "no islands". `gpu` is read the same way, after the picture.
134
+ const probe = (): Promise<IslandCount | null> =>
135
+ page
136
+ .evaluate(ISLAND_PROBE)
137
+ .then(parseIslandProbe)
138
+ .catch(() => null);
139
+ // The same budget again, no new flag: `settleMs` is when the runtime CALLS `import()`, so a
140
+ // mount gets as long to settle as the runtime got to start it; `--settle 0` still gets none.
141
+ const settle = (): Promise<IslandCount | null> =>
142
+ settleIslands(probe, { windowMs: options.settleMs, pollMs: SETTLE_POLL_MS, sleep });
143
+ let islands = await settle();
144
+ if (options.act !== undefined) {
145
+ await options.act(page, async () => {
146
+ islands = await settle();
147
+ return islands;
148
+ });
149
+ }
150
+ const bytes = await page.screenshot({ fullPage: options.fullPage });
151
+ // Read AFTER the capture, so an error logged while the page settled ships with its picture —
152
+ // and copied BEFORE the gpu probe: `requestAdapter()` may take seconds, and a page that
153
+ // redirects meanwhile must not have its new URL or its new logs reported beside the old picture.
154
+ const captured = {
155
+ finalUrl: page.url(),
156
+ capturedAt: (options.now ?? (() => new Date()))().toISOString(),
157
+ console: [...page.console()],
158
+ pageErrors: [...page.pageErrors()],
159
+ pageErrorsDropped: page.pageErrorsDropped(),
160
+ network: [...page.network()],
161
+ networkDropped: page.networkDropped(),
162
+ };
163
+ const gpu = await readShotGpu(page);
164
+ const verdict = buildVerdict({
165
+ route: options.route,
166
+ requestedUrl,
167
+ server: server.origin,
168
+ screenshot: SHOT_IMAGE,
169
+ bytes,
170
+ ...captured,
171
+ islands,
172
+ gpu,
173
+ landedStatus,
174
+ ...(options.expectStatus === undefined ? {} : { expectStatus: options.expectStatus }),
175
+ });
176
+ mkdirSync(options.outDir, { recursive: true });
177
+ const image = join(options.outDir, SHOT_IMAGE);
178
+ const verdictFile = join(options.outDir, SHOT_VERDICT);
179
+ await Bun.write(image, bytes);
180
+ await Bun.write(verdictFile, `${JSON.stringify(verdictJson(verdict), null, 2)}\n`);
181
+ return { verdict, image, verdictFile };
182
+ } finally {
183
+ // Bound to a const: narrowing a `let` does not survive into the closure below, and the session
184
+ // has to be closed from inside one so a teardown throw cannot replace the real failure.
185
+ const open = session;
186
+ if (open !== undefined) await quietly(() => open.close());
187
+ await quietly(() => server.stop());
188
+ }
189
+ }
@@ -9,6 +9,8 @@ import { t, validate } from '@ultimat3/schema';
9
9
  import type { ConsoleLine, NetworkEntry, PageError } from './browser-launcher-port';
10
10
  import { msg } from './messages';
11
11
  import type { JsonValue } from './output';
12
+ import type { ShotGpu } from './shot-gpu';
13
+ import { gpuJson } from './shot-gpu';
12
14
 
13
15
  /**
14
16
  * The one expression that counts islands, and it counts TWO different facts because they are two
@@ -156,6 +158,8 @@ export interface ShotInput {
156
158
  readonly landedStatus?: number | null | undefined;
157
159
  /** `--expect-status`: the one status this shot is ok with. Absent means any 2xx. */
158
160
  readonly expectStatus?: number | undefined;
161
+ /** The GPU backend the page could reach (`shot-gpu.ts`); absent or `null` when not read. */
162
+ readonly gpu?: ShotGpu | null | undefined;
159
163
  }
160
164
 
161
165
  export interface ShotVerdict extends ShotInput {
@@ -324,6 +328,7 @@ export function verdictJson(verdict: ShotVerdict): JsonValue {
324
328
  })),
325
329
  },
326
330
  islands: islandJson(verdict.islands),
331
+ gpu: gpuJson(verdict.gpu),
327
332
  network: {
328
333
  requests: verdict.network.length,
329
334
  refused: verdict.refused,
@@ -0,0 +1,85 @@
1
+ // The package names a tsconfig's `compilerOptions.paths` answers for, read through its `extends`
2
+ // chain. An alias resolves through the compiler and Bun's own tsconfig reading, never through
3
+ // `node_modules`, so a rule asking "is this import declared?" must not treat one as a package.
4
+
5
+ import { dirname, isAbsolute, join } from 'node:path'; // why: Bun exposes no path primitives.
6
+ import { packageOfSpecifier } from './workspace-graph';
7
+
8
+ type JsonObject = Readonly<Record<string, unknown>>;
9
+
10
+ const asRecord = (value: unknown): JsonObject | undefined =>
11
+ typeof value === 'object' && value !== null && !Array.isArray(value)
12
+ ? (value as JsonObject)
13
+ : undefined;
14
+
15
+ /** JSONC: a tsconfig may carry comments and trailing commas. Absent or unreadable says nothing. */
16
+ async function readTsconfig(path: string): Promise<JsonObject | undefined> {
17
+ const file = Bun.file(path);
18
+ if (!(await file.exists())) return undefined;
19
+ try {
20
+ return asRecord(Bun.JSONC.parse(await file.text()));
21
+ } catch {
22
+ return undefined;
23
+ }
24
+ }
25
+
26
+ /**
27
+ * Where one `extends` entry points. Relative and absolute paths as TypeScript reads them (`.json`
28
+ * appended when absent); a package specifier through Bun's resolver, trying the package's own
29
+ * `tsconfig.json` first as TypeScript does. A specifier that does not resolve says nothing.
30
+ */
31
+ function extendedPath(entry: string, from: string): string | undefined {
32
+ if (entry.startsWith('.') || isAbsolute(entry)) {
33
+ const path = isAbsolute(entry) ? entry : join(from, entry);
34
+ return path.endsWith('.json') ? path : `${path}.json`;
35
+ }
36
+ const candidates = entry.endsWith('.json') ? [entry] : [`${entry}/tsconfig.json`, entry];
37
+ for (const candidate of candidates) {
38
+ try {
39
+ return Bun.resolveSync(candidate, from);
40
+ } catch {
41
+ // The next spelling, then nothing.
42
+ }
43
+ }
44
+ return undefined;
45
+ }
46
+
47
+ /**
48
+ * The effective `paths` of the tsconfig at `path`: its own when it declares any, else the last
49
+ * `extends` entry's that does — TypeScript replaces `paths` wholesale, never merges it. `seen`
50
+ * stops a cycle, which TypeScript refuses and this must not loop on.
51
+ */
52
+ async function effectivePaths(
53
+ path: string,
54
+ seen: Set<string> = new Set(),
55
+ ): Promise<JsonObject | undefined> {
56
+ if (seen.has(path)) return undefined;
57
+ seen.add(path);
58
+ const config = await readTsconfig(path);
59
+ if (config === undefined) return undefined;
60
+ const own = asRecord(asRecord(config['compilerOptions'])?.['paths']);
61
+ if (own !== undefined) return own;
62
+ const extended = config['extends'];
63
+ const entries =
64
+ typeof extended === 'string' ? [extended] : Array.isArray(extended) ? extended : [];
65
+ let inherited: JsonObject | undefined;
66
+ for (const entry of entries) {
67
+ if (typeof entry !== 'string') continue;
68
+ const target = extendedPath(entry, dirname(path));
69
+ const paths = target === undefined ? undefined : await effectivePaths(target, seen);
70
+ if (paths !== undefined) inherited = paths;
71
+ }
72
+ return inherited;
73
+ }
74
+
75
+ /** Every package name the `tsconfig.json` in each of `dirs` aliases, unioned. */
76
+ export async function tsconfigAliases(dirs: readonly string[]): Promise<ReadonlySet<string>> {
77
+ const aliases = new Set<string>();
78
+ for (const dir of dirs) {
79
+ for (const key of Object.keys((await effectivePaths(join(dir, 'tsconfig.json'))) ?? {})) {
80
+ const name = packageOfSpecifier(key.replace(/\/?\*.*$/, ''));
81
+ if (name !== undefined) aliases.add(name);
82
+ }
83
+ }
84
+ return aliases;
85
+ }
@@ -6,7 +6,7 @@
6
6
  import { join, relative, resolve } from 'node:path';
7
7
  import { renderFixShellArg } from '@ultimat3/core';
8
8
  import type { AffectedSelection } from './affected';
9
- import { changedFiles, gitRoot, readAffectedSelection } from './affected';
9
+ import { changedFiles, gitRoot, readAffectedSelection, resolveSelection } from './affected';
10
10
  import type { AppTestScope } from './affected-tests';
11
11
  import { appTestScope, narrowToApp } from './affected-tests';
12
12
  import { BadFlagError } from './errors';
@@ -63,8 +63,9 @@ export async function changedScope(options: {
63
63
  /** Injected by tests; the real one is the suites' own discovery, every type. */
64
64
  readonly discover?: (root: string) => Promise<readonly string[]>;
65
65
  }): Promise<ChangedScope> {
66
- const selection = readAffectedSelection(options.args, 'verify');
66
+ const request = readAffectedSelection(options.args, 'verify');
67
67
  const checkout = await gitRoot(options.runner, options.root, 'verify');
68
+ const selection = await resolveSelection(options.runner, checkout, request);
68
69
  const files = await changedFiles(options.runner, {
69
70
  cwd: checkout,
70
71
  command: 'verify',
@@ -62,6 +62,7 @@ import { fromExec, fromFindings, hostFindings } from './verify-step';
62
62
  import { TEST_STEPS } from './verify-tests';
63
63
  import { typecheckArgs } from './verify-typecheck';
64
64
  import { checkPackageShape, fileSizeReport, hasWorkspacePackages } from './workspace-checks';
65
+ import { checkExternalDependencies } from './workspace-external-deps';
65
66
  import { checkWorkspaceDependencies } from './workspace-graph';
66
67
 
67
68
  /** The one file that makes the `roadmap` step answerable, and therefore what `applies` reads. */
@@ -158,6 +159,7 @@ export const VERIFY_STEPS: readonly VerifyStep[] = [
158
159
  fromFindings([
159
160
  ...(await checkPackageShape(ctx.root)),
160
161
  ...(await checkWorkspaceDependencies(ctx.root)),
162
+ ...(await checkExternalDependencies(ctx.root)),
161
163
  ]),
162
164
  },
163
165
  {
@@ -0,0 +1,164 @@
1
+ // Every registry package a workspace's shipped source imports is declared in THAT workspace's own
2
+ // manifest. Bun hoists one copy to the root `node_modules`, so an import a sibling happens to declare
3
+ // resolves for `tsc`, `boundaries` and the tests alike — until a clean or filtered install stops
4
+ // hoisting it and CI breaks on a tree every step called green (`bitecs`, an adopter, v31).
5
+
6
+ // why: Bun has no native "is this specifier a runtime builtin" predicate; `bun` and `bun:*` included.
7
+ import { isBuiltin } from 'node:module';
8
+ import { join } from 'node:path'; // why: Bun exposes no path-join primitive.
9
+ import { ERROR_DOCS_URL, renderFixShellArg } from '@ultimat3/core';
10
+ import { scanRuntimeImports, stripShebang } from './import-scan';
11
+ import type { Finding } from './output';
12
+ import { FIXTURE_SUFFIX } from './publish-closure';
13
+ import { eachSourceFile, isGenerated, isTest } from './source-files';
14
+ import { tsconfigAliases } from './tsconfig-aliases';
15
+ import { importedPackages, packageOfSpecifier, scanWorkspaces } from './workspace-graph';
16
+
17
+ /** Every field a package manager installs from — the same four `workspace-graph` reads. */
18
+ const DEPENDENCY_FIELDS = [
19
+ 'dependencies',
20
+ 'devDependencies',
21
+ 'peerDependencies',
22
+ 'optionalDependencies',
23
+ ] as const;
24
+
25
+ const asRecord = (value: unknown): Readonly<Record<string, unknown>> | undefined =>
26
+ typeof value === 'object' && value !== null && !Array.isArray(value)
27
+ ? (value as Record<string, unknown>)
28
+ : undefined;
29
+
30
+ /** JSONC: a tsconfig may carry comments; absent and unreadable both mean "declares nothing". */
31
+ async function readObject(path: string): Promise<Readonly<Record<string, unknown>> | undefined> {
32
+ const file = Bun.file(path);
33
+ if (!(await file.exists())) return undefined;
34
+ try {
35
+ return asRecord(Bun.JSONC.parse(await file.text()));
36
+ } catch {
37
+ return undefined;
38
+ }
39
+ }
40
+
41
+ /** name → range, across every installing field; the first field to declare a name wins. */
42
+ const declaredOf = (
43
+ manifest: Readonly<Record<string, unknown>> | undefined,
44
+ ): Map<string, string> => {
45
+ const declared = new Map<string, string>();
46
+ for (const field of DEPENDENCY_FIELDS) {
47
+ for (const [name, range] of Object.entries(asRecord(manifest?.[field]) ?? {})) {
48
+ if (!declared.has(name)) declared.set(name, typeof range === 'string' ? range : '');
49
+ }
50
+ }
51
+ return declared;
52
+ };
53
+
54
+ /** `@types/scope__name` types `@scope/name`; `@types/name` types `name`. */
55
+ const typesPackageFor = (name: string): string =>
56
+ `@types/${name.startsWith('@') ? name.slice(1).replace('/', '__') : name}`;
57
+
58
+ /**
59
+ * `@types/<pkg>` types a package; it does not install it. It covers a TYPE-ONLY import (`import
60
+ * type`, `typeof import()`) and never a runtime one, which still needs the package itself.
61
+ */
62
+ const covers = (declared: ReadonlyMap<string, string>, name: string, typeOnly: boolean): boolean =>
63
+ declared.has(name) || (typeOnly && declared.has(typesPackageFor(name)));
64
+
65
+ /** The packages a file needs at RUNTIME: what survives type erasure. */
66
+ const runtimePackages = (source: string, path: string): ReadonlySet<string> =>
67
+ new Set(
68
+ scanRuntimeImports({ path, source: stripShebang(source) }).flatMap((specifier) => {
69
+ const name = packageOfSpecifier(specifier);
70
+ return name === undefined ? [] : [name];
71
+ }),
72
+ );
73
+
74
+ /**
75
+ * Whether the file names the package itself. Bun's transpiler injects `react/jsx-dev-runtime` into
76
+ * every `.tsx` scan — an import the author never wrote and the app's `jsxImportSource` replaces —
77
+ * so a package only counts when a quoted specifier in the text starts with its name.
78
+ */
79
+ const spelledIn = (source: string, name: string): boolean =>
80
+ new RegExp(`['"\`]${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?:['"\`/])`).test(source);
81
+
82
+ interface Owner {
83
+ readonly dir: string;
84
+ readonly name: string;
85
+ readonly declared: ReadonlyMap<string, string>;
86
+ /** Root and workspace tsconfig `paths` aliases, each read through its `extends` chain. */
87
+ readonly aliases: ReadonlySet<string>;
88
+ }
89
+
90
+ export const undeclaredExternalDepFinding = (
91
+ owner: { readonly dir: string },
92
+ dependency: string,
93
+ at: string,
94
+ range?: string,
95
+ ): Finding => {
96
+ // The range a sibling already pins, when it travels through a shell verbatim: one version of a
97
+ // package across the app, rather than whatever the registry calls latest today.
98
+ const pinned = range === undefined ? dependency : `${dependency}@${range}`;
99
+ const spec = renderFixShellArg(pinned, '') === '' ? dependency : pinned;
100
+ const dev = at.endsWith(FIXTURE_SUFFIX) ? ' --dev' : '';
101
+ return {
102
+ code: 'X_WORKSPACE_EXTERNAL_DEP_UNDECLARED',
103
+ cause: `${at} imports ${dependency}, which neither ${owner.dir}/package.json nor the root package.json declares — it resolves only while another workspace's copy is hoisted`,
104
+ fix: `bun add ${renderFixShellArg(spec, '<the package>')}${dev} --cwd ${renderFixShellArg(owner.dir, '<the workspace directory>')}`,
105
+ docs: ERROR_DOCS_URL,
106
+ at: `${owner.dir}/package.json`,
107
+ };
108
+ };
109
+
110
+ /**
111
+ * The declared registry graph must cover the imported one, per workspace. Workspace siblings are
112
+ * `checkWorkspaceDependencies`' question and are skipped here; `@ultimat3/*` in an app is a
113
+ * registry package like any other and must be declared. Tests are out of scope for the same reason
114
+ * they are there: they resolve through the root's devDependencies and never reach a tarball.
115
+ *
116
+ * One finding per (workspace, package) pair: the fix is one command, not one per import site.
117
+ */
118
+ export async function checkExternalDependencies(root: string): Promise<readonly Finding[]> {
119
+ const { nodes } = await scanWorkspaces(root);
120
+ if (nodes.length === 0) return [];
121
+ const workspaceNames = new Set(nodes.map((node) => node.name));
122
+ // The root's own declarations resolve from every workspace under every linker: the root
123
+ // `node_modules` is on each one's lookup path, hoisted or isolated. A SIBLING's is not.
124
+ const rootDeclared = declaredOf(await readObject(join(root, 'package.json')));
125
+ const owners: Owner[] = [];
126
+ for (const node of nodes) {
127
+ const manifest = await readObject(join(root, node.dir, 'package.json'));
128
+ // Unioned rather than the workspace's alone: `tsc -b` compiles a file under the workspace's
129
+ // tsconfig, while a root-level `tsc` or Bun's resolver may read the root's.
130
+ const aliases = await tsconfigAliases([root, join(root, node.dir)]);
131
+ owners.push({ dir: node.dir, name: node.name, declared: declaredOf(manifest), aliases });
132
+ }
133
+ // Deepest directory first: a nested workspace's files are its own, never its parent's.
134
+ owners.sort((left, right) => right.dir.length - left.dir.length);
135
+ // The range the app already uses for a package, from whichever manifest declares it first.
136
+ const ranges = new Map<string, string>();
137
+ for (const [name, range] of rootDeclared) ranges.set(name, range);
138
+ for (const owner of [...owners].sort((left, right) => left.dir.localeCompare(right.dir))) {
139
+ for (const [name, range] of owner.declared) if (!ranges.has(name)) ranges.set(name, range);
140
+ }
141
+ const findings: Finding[] = [];
142
+ const reported = new Set<string>();
143
+ for await (const path of eachSourceFile(root)) {
144
+ if (isTest(path) || isGenerated(path)) continue;
145
+ const owner = owners.find((candidate) => path.startsWith(`${candidate.dir}/`));
146
+ if (owner === undefined) continue;
147
+ const source = await Bun.file(join(root, path)).text();
148
+ const runtime = runtimePackages(source, path);
149
+ for (const name of importedPackages(source, path)) {
150
+ if (isBuiltin(name) || workspaceNames.has(name) || owner.aliases.has(name)) continue;
151
+ if (!spelledIn(source, name)) continue;
152
+ const typeOnly = !runtime.has(name);
153
+ if (covers(owner.declared, name, typeOnly) || covers(rootDeclared, name, typeOnly)) continue;
154
+ const pair = `${owner.dir} ${name}`;
155
+ if (reported.has(pair)) continue;
156
+ reported.add(pair);
157
+ const range = ranges.get(name);
158
+ findings.push(
159
+ undeclaredExternalDepFinding(owner, name, path, range === '' ? undefined : range),
160
+ );
161
+ }
162
+ }
163
+ return findings;
164
+ }
@@ -60,7 +60,7 @@ x version # CLI version
60
60
  | `x graph [--from <a> --to <b>]` · `x impact <file\|primitive\|entity>` | the app as one typed graph, each edge `declared`, `import` or `observed` · what an edit reaches | shipped |
61
61
  | `x client vendor <name>` · `x client customer --out <dir>` | one OpenAPI compiler, two clients: a third party's document into `apps/web/clients/<name>/` (`outbound()` + `t` schemas), or the app's own published document into a client with no framework import | shipped |
62
62
  | `x shot <route>` | photograph one route from a real browser, plus a `verdict.json` a picture cannot carry | shipped |
63
- | `x pr review\|resolve\|reply` | inline review threads — the ones `gh pr view --comments` does not show | shipped |
63
+ | `x pr review\|resolve\|reply` | inline review threads — the ones `gh pr view --comments` does not show — plus every review verdict, every PR comment, and which review bots did not review | shipped |
64
64
  | `x ci` | the workflow runs for this branch, and the findings inside the failed step's log; `x ci tested`: whether a push reuses a green PR run | shipped |
65
65
  | `x errors explain <CODE>` | code → cause, fix, docs | shipped |
66
66
  | `x docs "<question>"` | framework docs and this wiki, offline, from the install — the first lookup | shipped |
@@ -604,7 +604,7 @@ x verify merge <part.json…> [--json]
604
604
 
605
605
  **`--changed`**, `As of 31.0` — the steps whose inputs the diff touches, NOT A GATE RUN like `--only`
606
606
  and never beside it (`X_CLI_BAD_FLAG`). The diff is `x affected`'s: `<base>...HEAD`, `--base` default
607
- `main`, `--dirty` adds uncommitted and untracked work. Each file gets one rule, each rule selects
607
+ the remote-tracking default branch (`origin/HEAD`, else `origin/main`, else local `main`; `As of 31.1`), `--dirty` adds uncommitted and untracked work. Each file gets one rule, each rule selects
608
608
  steps; `data.changed` carries `{ base, dirty, files: [{ path, rule }], steps: [{ name, files }] }` and
609
609
  the human render one `step ← files` line per step. Fail-open: a path no rule speaks for runs the gate.
610
610
  Each suite but `eval` then runs only the test files the diff's import closure reaches — `x test
@@ -720,7 +720,7 @@ because it was slow ([#342](https://github.com/developerz-ai/ultimate/issues/342
720
720
  | `lint` | Biome: no `any`, no default exports, no bare `Error`, no raw colours, no hardcoded user-facing strings |
721
721
  | `boundaries` | surface and layer imports, resolved transitively; package tiers in a monorepo; an app's `guards/*.ts`. A guard may spawn a process (`check` is any async function): it runs under this step's deadline, so a slow one sets `stepTimeoutMs.boundaries` in `x.verify.json` |
722
722
  | `filesize` | a source file over 500 lines |
723
- | `package-shape` | a workspace package missing `README.md`, `CLAUDE.md`, `tsconfig.json`, `src/index.ts` |
723
+ | `package-shape` | a workspace package missing `README.md`, `CLAUDE.md`, `tsconfig.json`, `src/index.ts`; a workspace importing a sibling workspace it does not declare (`X_WORKSPACE_DEP_UNDECLARED`); a workspace's shipped source importing a registry package — `@ultimat3/*` included, type-only imports too — that neither its own `package.json` nor the root's declares (`X_WORKSPACE_EXTERNAL_DEP_UNDECLARED`, fix `bun add <pkg> --cwd <workspace>`). Builtins (`node:*`, `bun`, `bun:*`), workspaces and tsconfig `paths` aliases are exempt. `As of 31.1` |
724
724
  | `errors` | every `X_*` code has a runnable fix and a docs page |
725
725
  | `unit` | pure logic — services, money, policy predicates, matchers |
726
726
  | `contract` | action/query schemas, policy denials, emitted OpenAPI and MCP shapes |
@@ -1514,7 +1514,7 @@ x test [unit|contract|live|job|e2e|eval] [--filter path[,path…]] [--allow-empt
1514
1514
  | `--sample` | string | — | run at most N files of the selection, deterministically. A fast signal for the eval loop — **never a gate** |
1515
1515
  | `--workers` | string | one per 1.25 GiB of a `max(2.75 GiB, 25% of RAM)` budget, at most one per core (the gate's width) | worker count, 1 to 64; each worker gets its own template-cloned database |
1516
1516
  | `--affected` | boolean | off | narrow the selection to the tests the diff can break: in an app root, by import closure (the files `x affected` reports as `data.tests`); elsewhere, the workspaces the diff touches and everything that depends on them. `--base`/`--dirty` without it are refused, not ignored |
1517
- | `--base` | string | `main` | the ref to diff against, merge-base (`<base>...HEAD`). Needs `--affected` |
1517
+ | `--base` | string | `origin/HEAD`'s branch | the ref to diff against, merge-base (`<base>...HEAD`). Unset: `origin/HEAD`'s target, else `origin/main`, else local `main` — `x affected`'s default. Needs `--affected` |
1518
1518
  | `--dirty` | boolean | off | union the working tree in — uncommitted and untracked. Needs `--affected` |
1519
1519
  | `--seed` | string | — | replay one `simulateJobs` seed, the `N` an `X_JOB_SIM_INVARIANT` names: handed to every `bun test` child as `ULTIMATE_JOB_SIM_SEED`, which runs that seed alone. A uint32, else `X_CLI_BAD_FLAG`. The shard reproduce line does not carry it yet |
1520
1520
  | `-- <args>` | tail | — | handed to `bun test` verbatim, before the file list — `x test unit -- --coverage --bail`. The reproduce line carries it back. **`x test` is the only command that reads a `--` tail**: every other one refuses it (`X_CLI_BAD_FLAG`) rather than dropping it, which is what all of them did until 2026-09 |
@@ -1598,9 +1598,9 @@ x affected [--base <ref>] [--dirty] [--paths] [--json]
1598
1598
 
1599
1599
  | Flag | Type | Default | Meaning |
1600
1600
  |---|---|---|---|
1601
- | `--base` | string | `main` | the ref to diff against. The diff is `<base>...HEAD` — **three dots**, so it is measured from the merge-base and an unrelated commit on `main` does not widen the answer |
1601
+ | `--base` | string | `origin/HEAD`'s branch | the ref to diff against. The diff is `<base>...HEAD` — **three dots**, so it is measured from the merge-base and an unrelated commit on `main` does not widen the answer. Unset, the base is the **remote-tracking** default branch, as already fetched (never fetched for you): `origin/HEAD`'s target, else `origin/main`, else local `main` when there is no remote-tracking ref (`origin/HEAD` or `origin/main`) (`As of 31.1`). `data.base` names the ref used |
1602
1602
  | `--dirty` | boolean | off | union the working tree in: uncommitted changes plus untracked files |
1603
- | `--paths` | boolean | off | print bare directories, one per line, for piping. `--json` is byte-identical either way |
1603
+ | `--paths` | boolean | off | stdout is the directories alone, one per line — `bun test $(x affected --paths)`; notes and the `✓` summary go to stderr (`As of 31.1`). Under `--json` stdout stays the one document, and `data` is byte-identical either way |
1604
1604
 
1605
1605
  **Transitive, or it is worse than nothing.** `A → B → C` means a change in `C` must reach `A`; a single pass over an unordered list reaches only `B`, and a scoped run that misses a transitive dependent is a green checkmark on a broken repo. The graph it walks is the one every workspace's `package.json` declares — which is why `package-shape` refuses an undeclared cross-workspace import (`X_WORKSPACE_DEP_UNDECLARED`): an edge missing from a manifest is an edge missing from this answer, silently.
1606
1606
 
@@ -1612,6 +1612,8 @@ Three rules the set obeys:
1612
1612
  | a workspace's own `package.json` | that workspace only |
1613
1613
  | a `.md` | nothing. A doc has no compilation unit to re-check |
1614
1614
 
1615
+ **Why the default base is `origin/main`, not `main`.** Local `main` moves only on a pull, so in a checkout nobody pulls — or a worktree — it lags origin, and `main...HEAD` counts every file origin merged since as this branch's work. `origin/main` moves on any `git fetch`. `x verify --changed` and `x test --affected` read the same default.
1616
+
1615
1617
  **`--base` is the default and `--dirty` is opt-in, which is the reverse of the obvious design.** This repo runs several agents concurrently in **one checkout** (no worktrees), so a working-tree diff returns every agent's uncommitted work at once and the "affected" set quietly expands to nearly the whole monorepo — narrowing nothing while reading as though it did. A ref diff is stable under that. `--dirty` is the right answer for one developer iterating alone.
1616
1618
 
1617
1619
  **Typecheck is deliberately not scoped.** `bun run typecheck` is `tsc -b`, a project build over a shared `.tsbuildinfo`, so a "scoped" typecheck is either the whole project anyway or a weaker check. The time is in the tests, which is what `x test --affected` narrows.
@@ -1710,7 +1712,7 @@ x shot --all-islands [--json]
1710
1712
  | `--viewport` | absent — the driver's default size | `<w>x<h>[,<w>x<h>…]` in CSS pixels, `As of 2026-10` (#444): the route photographed **once per size** over one dev server, each into `<out>/<w>x<h>/` with its own `shot.png` and `verdict.json`; `ok` only when every size's verdict is, and the summary is the first failing size's. `x shot /pricing --viewport 390x844,820x1180,1440x900` replaces a hand-written browser script. With `--matrix` the list replaces the default pair. One flag holding a list, never repeated — the parser keeps a repeated flag's last value. A side outside `1..16384`, anything but digits around an `x` (`0x10`, `1e3`, `390.5`), an empty entry or the same size twice is `X_CLI_BAD_FLAG` before anything boots; refused beside `--island`/`--all-islands`, whose states declare their own `viewport` |
1711
1713
  | `--theme` | absent — the box's own preference and the app's own `theme.defaultMode` | `light` or `dark`, `As of 2026-09-19`. Both `prefers-color-scheme` is emulated **and** the scheme is stored as the visitor's choice under `THEME_STORAGE_KEY` before navigation — the boot script since 20.2.0 answers `defaultMode` before the OS, so emulation alone photographs a dark-default app dark whatever was asked (#489). The `ui.shot`/`ui.inspect`/`ui.interact` tools' `theme` is this flag. Refused beside `--island`, which photographs both themes |
1712
1714
 
1713
- **`verdict.json` is the half that gates**, and the more important of the two files: a picture cannot tell you the island threw or logged. It carries the console lines, the island counts, the canvas size, the network tallies — and `blind`, which names what this capture could **not** observe. A tool that silently omits what it cannot see is worse than one that says so.
1715
+ **`verdict.json` is the half that gates**, and the more important of the two files: a picture cannot tell you the island threw or logged. It carries the console lines, the island counts, the canvas size, the network tallies, `gpu` — `{ api, available, adapter, fallback }` from the page's `navigator.gpu.requestAdapter()`, recorded and never gating, `null` when the page answered no probe (`As of 31.1`) — and `blind`, which names what this capture could **not** observe. A tool that silently omits what it cannot see is worse than one that says so.
1714
1716
 
1715
1717
  `ok` is decided by `buildVerdict` in `packages/cli/src/shot-verdict.ts` — read it there rather than trusting a count here: **nothing logged an error**, **nothing threw**, **no island failed to mount**, **the document photographed is the route asked for**, and **the document answered 2xx** (or exactly `--expect-status`; `status` and `expectedStatus` ride `verdict.json`, `null` when no response was seen — unseen never gates). A failed subresource — a missing favicon — is counted under `network.failed` and never gates. The island condition is new in 8.0.0: before it, every island's `mount()` could reject and the run still reported `ok: true`, "clean". The last matters most: a route behind `auth: 'required'` photographs the sign-in page and reports every island missing, which reads as a bug in the app when it is a bug in the capture.
1716
1718
 
@@ -1803,9 +1805,11 @@ Two hazards it encodes, both of which have bitten in this repo:
1803
1805
 
1804
1806
  It reads `latestOpinionatedReviews`, not `reviews(last: n)`: the most recent reviews are often all `COMMENTED` at the current head, so dating the decision from "the newest review" reports a stale `CHANGES_REQUESTED` as current — the hazard, inverted.
1805
1807
 
1808
+ **`--json` carries the whole conversation, additively** (as of 2026-11, 31.1.0): beside `threads`, `reviews` (every review: `state` — `APPROVED`, `CHANGES_REQUESTED`, `COMMENTED`, … — `author`, `isBot`, `commit`, `stale`, `body`), `comments` (the PR's issue comments, `updatedAt` included), `reviewsTruncated`/`commentsTruncated` (newest 50 each), and `bots` — one row per review bot: `{ login, reviews, comments, lastReviewAt, notice, blocked }`. `notice` is the newest "did not review" notice the bot posted as a PR comment — recognised by CodeRabbit's `<!-- … by coderabbit.ai -->` tag or a heading that begins with the notice's title, never by a phrase in prose; a submitted review is never one (`kind: 'rate-limited'` — CodeRabbit's rate or review limit; `kind: 'skipped'` — review skipped, too many files), and `blocked: true` means no review of its came after it: no new threads is a review that never happened, not a clean one. Bodies are clamped like thread bodies; `--full` lifts it. Same one GraphQL round trip. The human render adds one count line and, per bot with a notice, one line: `<bot> did not review: …` when blocked, else `<bot> posted a … notice at …, then reviewed at …`.
1809
+
1806
1810
  **Resolving closes a conversation, not a finding.** Whether the code is fixed is a fact no GitHub mutation observes, and `x pr resolve` says so rather than implying otherwise.
1807
1811
 
1808
- `x ci` exists because *"`gh run view` prints a tree of ticks and one cross, and the error is inside a per-job log that is mostly setup noise."* For a `verify` job the log tail **is** the findings block — this repo's gate already prints `X_*` codes and executable `fix:` lines — so `x ci` reads them back out into `findings[]` in the standard shape. `ok: false` iff a run failed; `ok: true` means *no failed run* — an in-flight or queued run still completes with `ok: true` and is reported through the `running > 0` line and a per-run `headSha`, not as a green verdict. `x pr review` always exits 0, because unresolved threads are the work to do, not a failure of the command that listed them. The two flags narrow the `gh run list` server-side — `--workflow` takes the workflow name or filename (`ci.yml`), `--event` takes `push|pull_request|workflow_dispatch` — so `x ci --workflow ci.yml --event push --branch main` answers *"is main's push CI green"* instead of folding every main-branch workflow into one verdict.
1812
+ `x ci` exists because *"`gh run view` prints a tree of ticks and one cross, and the error is inside a per-job log that is mostly setup noise."* For a `verify` job the log tail **is** the findings block — this repo's gate already prints `X_*` codes and executable `fix:` lines — so `x ci` reads them back out into `findings[]` in the standard shape. `cause` and `fix` are the text the gate wrote, with every transport wrapper undone — `##[group]`, `##[error]`/`##[warning]` prefixes, an echoed `::error …::` command (its `%0A` decoded), and a `<comment id=…>` fence a nested `x ci` printed; the log's foreign origin is `source: 'ci-log'` and the job `meta.job` — printed on the finding's head as `[from=ci-log <job>]` — never markup inside `fix`. `ok: false` iff a run failed; `ok: true` means *no failed run* — an in-flight or queued run still completes with `ok: true` and is reported through the `running > 0` line and a per-run `headSha`, not as a green verdict. `x pr review` always exits 0, because unresolved threads are the work to do, not a failure of the command that listed them. The two flags narrow the `gh run list` server-side — `--workflow` takes the workflow name or filename (`ci.yml`), `--event` takes `push|pull_request|workflow_dispatch` — so `x ci --workflow ci.yml --event push --branch main` answers *"is main's push CI green"* instead of folding every main-branch workflow into one verdict.
1809
1813
 
1810
1814
  **`x ci tested` answers whether a push may reuse a green pull-request run** — `{ tested, condition, reason, pr?, run? }`, for `GITHUB_SHA` or `HEAD`. `tested: true` needs all of: the subject ends `(#N)`; PR N merged as this very commit; its head is in this repository (a fork's run is never reused); its head tree is this tree; the newest same-repository run of `--workflow` (default `ci.yml`) on that head concluded `success`, under `--max-age` old (default `24h`: the runner image and the registry move). Any doubt — a condition unmet, `gh` absent, an API that did not answer — is `tested: false` and a full run. Exit 0 on every answer, so a workflow reads `data.tested`; only an unreadable `--max-age` refuses (`X_CLI_BAD_FLAG`). The workflow shape that consumes it: [CI-Parallel-Gate](CI-Parallel-Gate.md#a-push-a-green-pr-run-already-tested). As of 2026-11.
1811
1815
 
package/wiki/Upgrading.md CHANGED
@@ -185,6 +185,12 @@ One lookup for entries 32–38, 41, 43 and 50. A backend is swapped in ONE place
185
185
 
186
186
  A setter still on a package's `.` barrel is `X_ADAPTER_PORT_INCOMPLETE` on the `boundaries` step unless `scripts/lib/adapter-port-pins.ts` names why it selects no backend.
187
187
 
188
+ ### Not breaking, but you will see it
189
+
190
+ | What moved | Do |
191
+ |---|---|
192
+ | `x verify`'s `manifest` step is red, `X_MCP_APP_UNMOUNTED`, when `ai.mcp.expose` is `true` — **the default**, so an `app.config.ts` that never names it counts — and no `apps/web/mcp.ts` exports `mcp` (`As of 30.4.0`; before, the boot only logged it while `POST /mcp` answered 404). An app scaffolded before `x new` wrote that file hits it on its first 31.0.0 gate | mount it as `x new` does: `apps/web/mcp.ts` exporting `export const mcp = appMcp({ resolveToken: resolveAgentToken })`, `appMcp` from your `@<app>/mcp` package and `resolveAgentToken` from `./app/auth/agent-token` — copy those files (and `packages/mcp/src/index.ts`, if you have no `@<app>/mcp`) from a fresh `bunx create-ultimate`. With no catalog package, the error's own fix is the whole file: `export const mcp = defineAppMcp({ include: 'exposed', resolveToken })` (`@ultimat3/mcp`), `resolveToken` answering an agent or `null`. No agent surface wanted: `ai: { mcp: { expose: false } }` in `app.config.ts` |
193
+
188
194
  ## 29.x → 30.0.0, entry by entry
189
195
 
190
196
  Released 2026-11-07: `CHANGELOG.md`'s `## 30.0.0` breaking entries in their order, grouped by package, lowest tier first. No legacy path, no codemod, no shim. Rows are never renumbered; each row's `CHANGELOG.md` line names it as `(#N)` after the dash.
@@ -3760,7 +3766,7 @@ Job code never changes across a driver: `steps` is a driver member, so step pers
3760
3766
  |---|---|---|
3761
3767
  | tier 1 → tier 2 | `live: true` on the query | needs a `replicator` role and `orderBy` + `limit` on the `sql` |
3762
3768
  | tier 2 → tier 3 | `persist: true` on the **entity** | shipped in 21.0.0, opt-in per entity. No new mutators, no new authz, no new server code ([Realtime](Realtime#tier-3-shipped-in-2100)) |
3763
- | `memory` → `nats` transport | `realtime.transport: 'nats'`, and **`realtime.urlEnv`** — the env *key name*, not a URL (default `NATS_URL`). There is no `realtime.url` field | roll `sync` and `replicator`; clients reconnect with server-directed backoff. **`realtime.transport` decides the bus** (`selectTransport(env, { transport, urlEnv })`), `As of 2026-09-23` (in the tree, not yet tagged): `'nats'` with its variable unset refuses the boot, and so does `'memory'` with `NATS_URL` set (`X_CONFIG_INVALID`). On 21.x the presence of `NATS_URL` decided it and the config field was never read ([Configuration](Configuration)) |
3769
+ | `memory` → `nats` transport | set **`NATS_URL`** for every realtime role — the variable decides the bus. There is no `realtime.transport` or `realtime.urlEnv` key (removed in 31.0.0, entry 35); any other `Transport` is `transport` in `apps/<app>/runtime.ts` | roll `sync` and `replicator`; clients reconnect with server-directed backoff. From 22.0.0 to 30.x `realtime.transport` decided the bus and `'nats'` with its variable unset refused the boot (`X_CONFIG_INVALID`); on 21.x, as again from 31.0.0, the presence of `NATS_URL` decides it ([Realtime](Realtime), [Adapters](Adapters#transport)) |
3764
3770
 
3765
3771
  ## Where the facts live
3766
3772