@ultimat3/cli 31.0.0 → 31.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/CLAUDE.md +6 -1
  2. package/package.json +29 -29
  3. package/src/affected-base.ts +51 -0
  4. package/src/affected.ts +29 -10
  5. package/src/binding-names.ts +124 -0
  6. package/src/browser-transport.ts +28 -0
  7. package/src/ci-log.ts +76 -13
  8. package/src/cmd-affected-spec.ts +7 -3
  9. package/src/cmd-affected.ts +91 -77
  10. package/src/cmd-ci.ts +6 -3
  11. package/src/cmd-doctor.ts +8 -0
  12. package/src/cmd-exercise.ts +13 -1
  13. package/src/cmd-pr-spec.ts +1 -1
  14. package/src/cmd-pr.ts +72 -1
  15. package/src/cmd-shot.ts +13 -271
  16. package/src/cmd-test-spec.ts +2 -2
  17. package/src/cmd-upgrade.ts +28 -4
  18. package/src/cmd-verify-spec.ts +2 -2
  19. package/src/doctor-typescript.ts +31 -0
  20. package/src/error-codes-package.ts +38 -0
  21. package/src/error-codes.ts +7 -21
  22. package/src/mcp-errors-shot.ts +49 -0
  23. package/src/mcp-errors.ts +7 -41
  24. package/src/measure-scope.ts +17 -4
  25. package/src/messages-gate.ts +6 -0
  26. package/src/messages-upgrade.ts +2 -0
  27. package/src/offline-ports.ts +106 -0
  28. package/src/output.ts +21 -3
  29. package/src/pr-activity.ts +150 -0
  30. package/src/pr-bots.ts +109 -0
  31. package/src/pr-threads.ts +7 -2
  32. package/src/prerender.ts +2 -2
  33. package/src/runtime-storage-boot.ts +41 -7
  34. package/src/shot-gpu.ts +61 -0
  35. package/src/shot-route.ts +95 -0
  36. package/src/shot-run.ts +189 -0
  37. package/src/shot-verdict.ts +5 -0
  38. package/src/templates/scaffold-repo.ts +2 -1
  39. package/src/templates/sign-in-oidc.ts +24 -9
  40. package/src/transport-calls.ts +7 -3
  41. package/src/transport-values.ts +59 -0
  42. package/src/tsconfig-aliases.ts +85 -0
  43. package/src/typescript-floor.ts +83 -0
  44. package/src/upgrade-report.ts +8 -1
  45. package/src/verify-changed-scope.ts +3 -2
  46. package/src/verify-checks.ts +2 -0
  47. package/src/workspace-external-deps.ts +164 -0
  48. package/wiki/CLI-Reference.md +12 -8
  49. package/wiki/Upgrading.md +24 -5
package/src/mcp-errors.ts CHANGED
@@ -7,6 +7,7 @@ import type { ErrorExplanation } from '@ultimat3/mcp';
7
7
  import type { CliErrorCode } from './error-codes';
8
8
  import { CLI_ERROR_CODES } from './error-codes';
9
9
  import { codeFixes, codeFixScan } from './error-fixes';
10
+ import { SHOT_FIXES } from './mcp-errors-shot';
10
11
 
11
12
  /**
12
13
  * One runnable command per CLI code. Typed over `CliErrorCode`, so a new code fails the build.
@@ -70,47 +71,8 @@ const CLI_FIXES: Readonly<Record<CliErrorCode, string>> = {
70
71
  'x verify --json # the package-shape finding carries the dependency line to add',
71
72
  X_PACKAGE_DUPLICATED:
72
73
  'x i18n check --json # the finding names both copies and the package.json to pin',
73
- X_SHOT_BROWSER_MISSING:
74
- 'export CHROME_PATH=/usr/bin/google-chrome # macOS: "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"; Windows PowerShell: $env:CHROME_PATH = "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"',
75
- X_UI_SHOT_ROUTE_UNKNOWN:
76
- 'x routes --json # then call the ui.* tool with one of its path values',
77
- X_UI_SHOT_ROUTE_UNBUDGETED:
78
- "x build --target static --json && x verify --only budgets --json # after declaring budget: { js: '<n>kb' } in the route file",
79
- // The four `ui.interact` refusals. None can be repaired by a command — each is a change to the
80
- // step list the agent sends — so each names the command that SHOWS what a valid resend needs.
81
- X_UI_INTERACT_STEPS_INVALID:
82
- 'x help shot --json # then resend ui.interact with at most 12 one-key steps, type.text under 500 chars and wait under 5000 ms',
83
- X_UI_INTERACT_SECRET_FIELD:
84
- 'x shot --all-islands --json # or --island <name>: a declared state renders the filled form without the secret ever being typed',
85
- X_UI_INTERACT_LEFT_APP:
86
- 'x routes --json # then resend ui.interact with steps that stay on one of its paths',
87
- X_UI_INTERACT_STEP_FAILED:
88
- 'x routes --json # then run ui.inspect on the route first and copy a selector it reports with count >= 1',
89
- X_SHOT_HOST_REFUSED: 'x shot /route --allow-hosts cdn.example.com --json',
90
- X_SHOT_ELEMENT_MISSING:
91
- 'x routes --json # then run ui.inspect on the route first and copy a selector it reports with count >= 1',
92
- X_SHOT_ELEMENT_UNREADY:
93
- 'x routes --json # then run ui.inspect on the route first and copy a selector it reports with count >= 1',
94
- X_SHOT_KEY_INVALID: 'x help shot --json # a chord is modifiers then one key: Meta+K',
95
- // The three `ui.diff` codes. Every capture it can compare was written by `x shot` or a `ui.*`
96
- // tool under `.x/shot/`, so the runnable half is the command that writes one there.
97
- X_UI_DIFF_PATH_OUTSIDE:
98
- 'x shot / --json # then pass the image path it answers, relative to the app root: ui.diff reads .x/shot/ and nothing else',
99
- X_UI_DIFF_FILE_MISSING:
100
- 'x shot / --json # then diff the image path it answers; a capture ui.shot wrote is listed in its own answer',
101
- X_UI_DIFF_SIZE_MISMATCH:
102
- 'x shot / --json # photograph both captures at one viewport with one fullPage setting, then diff those two',
103
- // The four island-capture codes. Each one's real repair is an edit to the app's own states file
104
- // or component, which no command can perform — so each names the command that REPRODUCES it with
105
- // the file and the reason attached, which is the runnable half.
106
- X_SHOT_ISLAND_STATES_EMPTY:
107
- 'x help shot --json # then export the manifest from the states file the cause names',
108
- X_SHOT_ISLAND_UNPHOTOGRAPHABLE:
109
- 'x help shot --json # the cause names the assertion that did not hold; --settle buys the slow ones more time',
110
- X_SHOT_ISLAND_UNSTUBBED_REQUEST:
111
- 'x help shot --json # the cause lists every request the state must answer under routes',
112
- X_SHOT_ISLAND_MISSING:
113
- 'x help shot --json # every absent picture carries its own named refusal in the run above',
74
+ // `x shot` and the `ui.*` tools: their own family, in `mcp-errors-shot.ts`.
75
+ ...SHOT_FIXES,
114
76
  X_GH_UNAVAILABLE: 'gh auth login # install first from https://cli.github.com',
115
77
  X_GH_NOT_AUTHENTICATED: 'gh auth login',
116
78
  X_GH_COMMAND_FAILED: 'x ci --json # the finding carries the gh invocation that failed',
@@ -408,6 +370,10 @@ const CLI_FIXES: Readonly<Record<CliErrorCode, string>> = {
408
370
  'x verify --only manifest --json # after exporting partitions() from @ultimat3/jobs in a module listed under jobs in apps/web/api/index.ts, and its .schedule under tasks',
409
371
  X_BOUNDARY_LOADER_IMPORT:
410
372
  'export const api = defineApi({ actions: [yourActions], queries: [yourQueries] }); # in apps/web/api/index.ts — list the module there, then delete the loader import',
373
+ X_WORKSPACE_EXTERNAL_DEP_UNDECLARED:
374
+ 'x verify --only package-shape --json # each finding carries its own `bun add <package> --cwd <workspace>` line',
375
+ X_TYPESCRIPT_VERSION:
376
+ 'x doctor --json # each X_TYPESCRIPT_VERSION finding names its manifest and the bun add that moves it',
411
377
  };
412
378
 
413
379
  const isCliCode = (code: string): code is CliErrorCode =>
@@ -4,17 +4,21 @@
4
4
  // context (`useRequestHeader('cookie')` throws X_NO_REQUEST outside one), an actor the app chose
5
5
  // (`defineMeasurementActor()` in `app.config.ts`, core's `measurementActor()` otherwise), and a
6
6
  // server to answer — the app's own API pipeline, dispatched IN PROCESS through core's
7
- // `withInProcessFetch`, because no server is listening during a build (plan 101 slice 11 m).
7
+ // `withInProcessFetch`, because no server is listening during a build (plan 101 slice 11 m) — and
8
+ // `runtime.ts`'s ports as `offline-ports.ts` decides them, for every render the build runs.
8
9
 
9
10
  import type { Actor, Ctx } from '@ultimat3/core';
10
11
  import { actorLabel, measurementActor, runWithContext, withInProcessFetch } from '@ultimat3/core';
11
12
  import { defineHttpConfig, httpPipeline, httpRouter, requestContext } from '@ultimat3/http';
12
13
  import { apiRoutes } from './api-routes';
14
+ import { installOfflinePorts } from './offline-ports';
13
15
 
14
- /** One build's measurement scope: its actor, and a runner that renders inside it. */
16
+ /** One build's measurement scope: its actor, a runner that renders inside it, and its release. */
15
17
  export interface MeasureScope {
16
18
  readonly actor: Actor;
17
19
  run<T>(fn: () => T): T;
20
+ /** Releases the ports `measureScope` installed. Once, when the build's renders are done. */
21
+ close(): Promise<void>;
18
22
  }
19
23
 
20
24
  /** A scope's in-process API: the app's own table, as `actor` — or, `null`, as nobody. */
@@ -45,15 +49,24 @@ function inProcessRunner(input: ScopeInput, actor: Actor | null): <T>(fn: () =>
45
49
  return <T>(fn: () => T): T => withInProcessFetch(dispatch, () => runWithContext(request, fn));
46
50
  }
47
51
 
52
+ /** A measurement scope's input: the app at `root`, whose `runtime.ts` the build honours. */
53
+ interface MeasureInput extends ScopeInput {
54
+ readonly root: string;
55
+ }
56
+
48
57
  /**
49
58
  * The scope for `origin`. The pipeline is the app's API table and nothing else: a page's data
50
59
  * comes from its actions and queries, and a route the render reaches that is not one of them
51
60
  * answers 404 — which the render reports, and the route is filed unmeasured with that reason.
52
61
  * For a render that is WEIGHED and discarded only: its output is never published.
53
62
  */
54
- export async function measureScope(input: ScopeInput): Promise<MeasureScope> {
63
+ export async function measureScope(input: MeasureInput): Promise<MeasureScope> {
55
64
  const actor = await measurementActor();
56
- return { actor, run: inProcessRunner(input, actor) };
65
+ // Installed here rather than per render: the published (`site/`) renders read the same ports, and
66
+ // a page whose `load` calls an `audit: true` query was unmeasured with `X_AUDIT_SINK_MISSING`
67
+ // for an app that declared its sink in `runtime.ts`, as upgrade entry 43 says to.
68
+ const close = await installOfflinePorts(input.root);
69
+ return { actor, run: inProcessRunner(input, actor), close };
57
70
  }
58
71
 
59
72
  /**
@@ -37,6 +37,10 @@ export const GATE_MESSAGES = {
37
37
  'cli.ci.tested.api': 'not tested: GitHub did not answer ({detail}) — a full run',
38
38
  'cli.ci.tested.sha':
39
39
  'not tested: no GITHUB_SHA, and git rev-parse HEAD named no commit — a full run',
40
+ // A review bot that said it did NOT review leaves no thread, so its silence reads as a clean
41
+ // review unless a line says otherwise. `notice` is the same fact once the bot reviewed after it.
42
+ 'cli.pr.bot.blocked': ' {login} did not review: {excerpt} ({kind}, {at}) — {url}',
43
+ 'cli.pr.bot.notice': ' {login} posted a {kind} notice at {at}, then reviewed at {reviewed}',
40
44
  'cli.pr.body.truncated': ' … {hidden} more line(s) — re-run with --full',
41
45
  /** The line of a thread whose anchor GitHub answers null for — a value, not a column key. */
42
46
  'cli.pr.line.unknown': '-',
@@ -47,6 +51,8 @@ export const GATE_MESSAGES = {
47
51
  'thread {id} is marked resolved on GitHub — that records the conversation, not that the finding is fixed',
48
52
  'cli.pr.review.count':
49
53
  '{unresolved} unresolved and {resolved} resolved review thread(s) on {repo}#{pr}',
54
+ 'cli.pr.review.activity':
55
+ ' {reviews} review(s), {comments} PR comment(s), {bots} review bot(s) — bodies in --json',
50
56
  'cli.pr.review.current': ' submitted against the current head {head}',
51
57
  'cli.pr.review.decision': ' review: {decision} by {author} at {submitted}',
52
58
  'cli.pr.review.none': 'no review thread is anchored to a line on {repo}#{pr}',
@@ -26,6 +26,8 @@ export const UPGRADE_MESSAGES = {
26
26
  'AGENTS.md: differs from CLAUDE.md, left alone. Merge what only AGENTS.md says into CLAUDE.md, then: ln -sf CLAUDE.md AGENTS.md',
27
27
  'cli.upgrade.bunEdited': 'bun floor: {path} {from} -> {to}',
28
28
  'cli.upgrade.bunManual': 'bun floor, by hand: {path}:{line} — {why}',
29
+ 'cli.upgrade.typescript':
30
+ 'typescript, by hand: {file} declares {from}, below the {to} the framework is checked with — run: {fix}',
29
31
  'cli.upgrade.done': '{from} -> {to}: the gate is green',
30
32
  'cli.upgrade.dryRun': '{from} -> {to}: nothing written, no gate run',
31
33
  'cli.upgrade.guard': 'guard, yours to take or leave: {fix}',
@@ -0,0 +1,106 @@
1
+ // `apps/<app>/runtime.ts` for the two paths that run the app's primitives with no server — `x build`'s
2
+ // renders and `x exercise`'s pass — read and installed by the boot's own reader and loop, with
3
+ // every port first decided by `OFFLINE_PORTS`: a memory double, or the package default.
4
+
5
+ // Why a table and not the app's values: neither path may reach a deployment's backend. A port with
6
+ // no row is a build error (TS2741 on `OfflinePortTable`).
7
+
8
+ import { memoryAuditSink } from '@ultimat3/action';
9
+ import { loadAppRuntime } from './app-runtime';
10
+ import type { PortValues, RuntimeOverrides } from './runtime-overrides';
11
+ import { PORT_BINDINGS } from './runtime-port-bindings';
12
+ import type { ChosenPorts, WiredPort } from './runtime-ports';
13
+ import { installPorts } from './runtime-ports';
14
+
15
+ /**
16
+ * What an offline path does with a port `runtime.ts` supplied. `double`: install this stand-in in
17
+ * the app's place — the port's presence is what the primitive asks, and the app's own backend may
18
+ * be production's. `default`: install nothing, so the package's own default answers; `why` says so.
19
+ */
20
+ export type OfflineChoice<P extends WiredPort> =
21
+ | { readonly use: 'double'; readonly double: () => PortValues[P] }
22
+ | { readonly use: 'default'; readonly why: string };
23
+
24
+ export type OfflinePortTable = { readonly [P in WiredPort]: OfflineChoice<P> };
25
+
26
+ const remote = (why: string) => ({ use: 'default', why }) as const;
27
+ const NETWORK = remote('a remote backend; the package default (memory or a refusal) answers');
28
+ const POOL = remote('Postgres over the ambient pool by default: the scratch or measure database');
29
+ const BOOT = remote('a boot-phase port; the offline paths keep the process their command set up');
30
+ const SERVED = remote('read by the serving boot only; no request is served offline');
31
+
32
+ /**
33
+ * One row per wired port. Only `services`-phase ports can be doubles: `installPorts` installs that
34
+ * phase alone (`offline-ports.test.ts` holds it).
35
+ */
36
+ export const OFFLINE_PORTS: OfflinePortTable = {
37
+ aiGateway: NETWORK,
38
+ // Its presence is the contract: `audit: true` is refused without one (`X_AUDIT_SINK_MISSING`), so
39
+ // an app that declared one runs; where the records go is the deployment's, never a build's.
40
+ auditSink: { use: 'double', double: () => memoryAuditSink() },
41
+ authLimiter: POOL,
42
+ authServerStore: POOL,
43
+ cacheTiers: SERVED,
44
+ clock: BOOT,
45
+ embedder: NETWORK,
46
+ errorReporter: remote('an offline failure is the command`s finding, never a production report'),
47
+ eventBus: POOL,
48
+ failureStore: SERVED,
49
+ idempotencyStore: POOL,
50
+ images: SERVED,
51
+ isrStore: SERVED,
52
+ jobs: POOL,
53
+ mail: NETWORK,
54
+ mcpConfirmationStore: POOL,
55
+ meterStore: POOL,
56
+ notifyStores: POOL,
57
+ outboxStore: POOL,
58
+ purge: NETWORK,
59
+ pushSubscriptionStore: POOL,
60
+ rateLimitStore: POOL,
61
+ scrapeDriver: NETWORK,
62
+ searchIndex: POOL,
63
+ secretSource: BOOT,
64
+ semanticCache: NETWORK,
65
+ smsTransport: NETWORK,
66
+ storage: remote('`x exercise` stands in a memory disk (`exercise-services.ts`)'),
67
+ totpReplay: POOL,
68
+ transport: NETWORK,
69
+ uploadScanner: NETWORK,
70
+ };
71
+
72
+ /** The doubles for the ports `runtime` supplied; an absent port stays absent, as at a real boot. */
73
+ export function offlineChosen(
74
+ runtime: RuntimeOverrides | undefined,
75
+ table: OfflinePortTable = OFFLINE_PORTS,
76
+ ): ChosenPorts {
77
+ const chosen: { [P in WiredPort]?: PortValues[P] } = {};
78
+ const pick = <P extends WiredPort>(port: P): void => {
79
+ const choice: OfflineChoice<P> = table[port];
80
+ if (choice.use === 'double' && runtime?.[port] !== undefined) chosen[port] = choice.double();
81
+ };
82
+ for (const port of Object.keys(table) as WiredPort[]) pick(port);
83
+ return chosen;
84
+ }
85
+
86
+ /** Install the offline ports for the app at `root`; answers the release, newest first. */
87
+ export async function installOfflinePorts(root: string): Promise<() => Promise<void>> {
88
+ const releases = await installPorts(
89
+ PORT_BINDINGS,
90
+ 'services',
91
+ offlineChosen(await loadAppRuntime(root)),
92
+ );
93
+ return async () => {
94
+ for (const release of releases.toReversed()) await release();
95
+ };
96
+ }
97
+
98
+ /** `work` with the offline ports installed, released however it ends. */
99
+ export async function withOfflinePorts<T>(root: string, work: () => Promise<T>): Promise<T> {
100
+ const release = await installOfflinePorts(root);
101
+ try {
102
+ return await work();
103
+ } finally {
104
+ await release();
105
+ }
106
+ }
package/src/output.ts CHANGED
@@ -33,8 +33,10 @@ export interface Finding {
33
33
  readonly at?: string;
34
34
  /**
35
35
  * Where the finding's TEXT came from, when not from this process. `'ci-log'` is `x ci` reading
36
- * a finding back out of a CI log that anyone who can push a branch writes: its `fix` is fenced
37
- * and must never be run as this CLI's own instruction.
36
+ * a finding back out of a CI log that anyone who can push a branch writes: its `fix` is the
37
+ * log's instruction, never this CLI's, and is never rewritten into a runnable one. The value
38
+ * stays the clean text — the provenance is this field, `meta.job`, and the `[from=ci-log …]`
39
+ * marker `renderFinding` prints on the head; never markup inside `fix`.
38
40
  */
39
41
  readonly source?: 'ci-log';
40
42
  /**
@@ -203,7 +205,7 @@ export function renderFinding(finding: Finding, indent = ''): string {
203
205
  : undefined;
204
206
  const stepLabel = typeof stepValue === 'string' ? ` [step=${singleLine(stepValue)}]` : '';
205
207
  const pathLabel = finding.at === undefined ? '' : ` (${singleLine(finding.at)})`;
206
- const head = `${code}${pathLabel}${stepLabel}`;
208
+ const head = `${code}${pathLabel}${stepLabel}${fromLabel(finding)}`;
207
209
  const lines = [
208
210
  `${indent}${head}`,
209
211
  `${indent} cause: ${singleLine(finding.cause)}`,
@@ -213,6 +215,22 @@ export function renderFinding(finding: Finding, indent = ''): string {
213
215
  return lines.join('\n');
214
216
  }
215
217
 
218
+ /**
219
+ * The provenance marker for a finding read out of a CI log, printed LAST on the head so the
220
+ * human render still says which findings came from outside (`x ci`) while `fix` stays the clean
221
+ * command. Brackets in a job name become parentheses: the marker must stay one bracketed token,
222
+ * and `ci-log`'s `LOCATOR` stands aside for exactly that token.
223
+ */
224
+ function fromLabel(finding: Finding): string {
225
+ if (finding.source !== 'ci-log') return '';
226
+ const job = finding.meta?.['job'];
227
+ const named =
228
+ typeof job === 'string' && job !== ''
229
+ ? ` ${singleLine(job).replaceAll('[', '(').replaceAll(']', ')')}`
230
+ : '';
231
+ return ` [from=ci-log${named}]`;
232
+ }
233
+
216
234
  /** Same format, but titled with the error's own summary line when it has one. */
217
235
  export function renderUltimateError(error: UltimateErrorShape, indent = ''): string {
218
236
  const summary = summaryOf(error);
@@ -0,0 +1,150 @@
1
+ // The rest of a pull request's conversation, beside its inline threads: every review with its
2
+ // verdict and body, and every ISSUE comment. A bot that said "I did not review this" says it in one
3
+ // of these two places and never in a thread, so `x pr review` asks for both in the same round trip.
4
+
5
+ import { t } from '@ultimat3/schema';
6
+
7
+ /** The newest reviews, and the newest issue comments, one page each. */
8
+ export const ACTIVITY_PAGE = 50;
9
+
10
+ /**
11
+ * The fragment `REVIEW_QUERY` (`pr-threads.ts`) splices into its `pullRequest` selection. `last`,
12
+ * not `first`: a long pull request's oldest conversation is the least likely to still matter, and
13
+ * a bot's "review limit" notice is by construction among the newest.
14
+ */
15
+ export const ACTIVITY_FIELDS =
16
+ `reviews(last:${ACTIVITY_PAGE}){totalCount nodes{id state body submittedAt url ` +
17
+ 'author{login __typename} commit{oid}}} ' +
18
+ `comments(last:${ACTIVITY_PAGE}){totalCount nodes{id body createdAt updatedAt url ` +
19
+ 'author{login __typename}}}';
20
+
21
+ const ACTOR = t.nullable(t.object({ login: t.string, __typename: t.string }));
22
+
23
+ /** The two connections, as `REVIEW_RESPONSE` declares them inside `pullRequest`. */
24
+ export const ACTIVITY_SCHEMA = {
25
+ reviews: t.object({
26
+ totalCount: t.number,
27
+ nodes: t.array(
28
+ t.object({
29
+ id: t.string,
30
+ state: t.string,
31
+ body: t.string,
32
+ submittedAt: t.nullable(t.string),
33
+ url: t.string,
34
+ author: ACTOR,
35
+ commit: t.nullable(t.object({ oid: t.string })),
36
+ }),
37
+ ),
38
+ }),
39
+ comments: t.object({
40
+ totalCount: t.number,
41
+ nodes: t.array(
42
+ t.object({
43
+ id: t.string,
44
+ body: t.string,
45
+ createdAt: t.string,
46
+ updatedAt: t.string,
47
+ url: t.string,
48
+ author: ACTOR,
49
+ }),
50
+ ),
51
+ }),
52
+ } as const;
53
+
54
+ /** One submitted review: a verdict (`APPROVED`, `CHANGES_REQUESTED`, `COMMENTED`, …) and its body. */
55
+ export interface PrReviewEntry {
56
+ readonly id: string;
57
+ readonly state: string;
58
+ readonly author: string;
59
+ readonly isBot: boolean;
60
+ readonly submittedAt: string | null;
61
+ readonly commit: string | null;
62
+ /** Submitted against a commit that is no longer the head — the same rule as `PrReview.stale`. */
63
+ readonly stale: boolean;
64
+ readonly url: string;
65
+ readonly body: string;
66
+ }
67
+
68
+ /** One comment on the pull request itself, not anchored to a line. */
69
+ export interface PrIssueComment {
70
+ readonly id: string;
71
+ readonly author: string;
72
+ readonly isBot: boolean;
73
+ readonly createdAt: string;
74
+ /** A bot edits its summary comment in place, so this — not `createdAt` — dates what it says. */
75
+ readonly updatedAt: string;
76
+ readonly url: string;
77
+ readonly body: string;
78
+ }
79
+
80
+ export interface PrActivity {
81
+ readonly reviews: readonly PrReviewEntry[];
82
+ readonly comments: readonly PrIssueComment[];
83
+ /** More reviews exist than one page holds. */
84
+ readonly reviewsTruncated: boolean;
85
+ /** More issue comments exist than one page holds. */
86
+ readonly commentsTruncated: boolean;
87
+ }
88
+
89
+ type Actor = { readonly login: string; readonly __typename: string } | null;
90
+
91
+ /** GitHub answers `null` for a deleted account; the row is kept under the name GitHub shows. */
92
+ const loginOf = (author: Actor): string => author?.login ?? 'ghost';
93
+
94
+ /** GraphQL types an app account `Bot`; a REST-shaped login ends in `[bot]`. Either is a bot. */
95
+ const isBot = (author: Actor): boolean =>
96
+ author !== null && (author.__typename === 'Bot' || author.login.endsWith('[bot]'));
97
+
98
+ interface ActivityInput {
99
+ readonly reviews: {
100
+ readonly totalCount: number;
101
+ readonly nodes: readonly {
102
+ readonly id: string;
103
+ readonly state: string;
104
+ readonly body: string;
105
+ readonly submittedAt: string | null;
106
+ readonly url: string;
107
+ readonly author: Actor;
108
+ readonly commit: { readonly oid: string } | null;
109
+ }[];
110
+ };
111
+ readonly comments: {
112
+ readonly totalCount: number;
113
+ readonly nodes: readonly {
114
+ readonly id: string;
115
+ readonly body: string;
116
+ readonly createdAt: string;
117
+ readonly updatedAt: string;
118
+ readonly url: string;
119
+ readonly author: Actor;
120
+ }[];
121
+ };
122
+ }
123
+
124
+ /** The parsed connections as rows, oldest first — the order the conversation happened in. */
125
+ export function activityOf(pull: ActivityInput, headSha: string): PrActivity {
126
+ return {
127
+ reviews: pull.reviews.nodes.map((review) => ({
128
+ id: review.id,
129
+ state: review.state,
130
+ author: loginOf(review.author),
131
+ isBot: isBot(review.author),
132
+ submittedAt: review.submittedAt,
133
+ commit: review.commit?.oid ?? null,
134
+ stale: review.commit?.oid !== headSha,
135
+ url: review.url,
136
+ body: review.body,
137
+ })),
138
+ comments: pull.comments.nodes.map((comment) => ({
139
+ id: comment.id,
140
+ author: loginOf(comment.author),
141
+ isBot: isBot(comment.author),
142
+ createdAt: comment.createdAt,
143
+ updatedAt: comment.updatedAt,
144
+ url: comment.url,
145
+ body: comment.body,
146
+ })),
147
+ reviewsTruncated: pull.reviews.totalCount > pull.reviews.nodes.length,
148
+ commentsTruncated: pull.comments.totalCount > pull.comments.nodes.length,
149
+ };
150
+ }
package/src/pr-bots.ts ADDED
@@ -0,0 +1,109 @@
1
+ // Which review bots spoke on a pull request, and whether one of them said it did NOT review it. A
2
+ // rate-limited or skipped bot leaves no thread and no verdict, so its silence reads exactly like a
3
+ // clean review unless something reads the notice it posted instead.
4
+
5
+ import type { PrIssueComment, PrReviewEntry } from './pr-activity';
6
+
7
+ export type BotNoticeKind = 'rate-limited' | 'skipped';
8
+
9
+ export interface BotNotice {
10
+ readonly kind: BotNoticeKind;
11
+ /** The notice's own heading or first line, so a reader sees which notice without the body. */
12
+ readonly excerpt: string;
13
+ }
14
+
15
+ export interface BotSummary {
16
+ readonly login: string;
17
+ readonly reviews: number;
18
+ readonly comments: number;
19
+ /** The bot's newest review that is not itself a notice; `null` when it never reviewed. */
20
+ readonly lastReviewAt: string | null;
21
+ /** The newest "did not review" notice it posted, wherever it posted it. */
22
+ readonly notice: (BotNotice & { readonly at: string; readonly url: string }) | null;
23
+ /** A notice exists and no review of the bot's came after it: its review is missing, not clean. */
24
+ readonly blocked: boolean;
25
+ }
26
+
27
+ /**
28
+ * The notices, known by their MARKERS and never by a phrase in prose: a review that discusses
29
+ * "rate limit exceeded" in an upstream API is a review, not a bot refusing to give one.
30
+ * CodeRabbit's own HTML comment tags come first; otherwise the notice is a markdown heading
31
+ * (quoted or not) that BEGINS with the notice's title.
32
+ */
33
+ const MARKERS: readonly { readonly kind: BotNoticeKind; readonly pattern: RegExp }[] = [
34
+ { kind: 'rate-limited', pattern: /<!--[^>]*rate limited by coderabbit\.ai[^>]*-->/i },
35
+ { kind: 'skipped', pattern: /<!--[^>]*skip review by coderabbit\.ai[^>]*-->/i },
36
+ ];
37
+ const HEADINGS: readonly { readonly kind: BotNoticeKind; readonly pattern: RegExp }[] = [
38
+ { kind: 'rate-limited', pattern: /^(?:rate limit exceeded|review limit reached)\b/i },
39
+ { kind: 'skipped', pattern: /^review skipped\b/i },
40
+ ];
41
+
42
+ /** A markdown heading line, quoted or not, as its title text; `undefined` for any other line. */
43
+ const headingOf = (line: string): string | undefined => {
44
+ const match = /^[>\s]*#{1,6}\s+(.+)$/.exec(line);
45
+ return match?.[1]?.replaceAll('*', '').trim();
46
+ };
47
+
48
+ /**
49
+ * The notice an ISSUE COMMENT states, or `null` for every ordinary body. A formal review is never
50
+ * passed here: whatever its body says, a submitted review is the bot having reviewed.
51
+ */
52
+ export function botNotice(body: string): BotNotice | null {
53
+ const headings = body
54
+ .replaceAll('\r\n', '\n')
55
+ .split('\n')
56
+ .flatMap((line) => {
57
+ const title = headingOf(line);
58
+ return title === undefined ? [] : [title];
59
+ });
60
+ for (const title of headings) {
61
+ const rule = HEADINGS.find((candidate) => candidate.pattern.test(title));
62
+ if (rule !== undefined) return { kind: rule.kind, excerpt: title.slice(0, 200) };
63
+ }
64
+ const marker = MARKERS.find((candidate) => candidate.pattern.test(body));
65
+ if (marker === undefined) return null;
66
+ return { kind: marker.kind, excerpt: (headings[0] ?? '').slice(0, 200) };
67
+ }
68
+
69
+ interface Spoken {
70
+ readonly at: string;
71
+ readonly url: string;
72
+ readonly notice: BotNotice | null;
73
+ }
74
+
75
+ const newest = <T extends { readonly at: string }>(rows: readonly T[]): T | null =>
76
+ rows.reduce<T | null>((best, row) => (best === null || row.at > best.at ? row : best), null);
77
+
78
+ /** One row per bot that reviewed or commented, in the order each first appears. */
79
+ export function botsSummary(
80
+ reviews: readonly PrReviewEntry[],
81
+ comments: readonly PrIssueComment[],
82
+ ): readonly BotSummary[] {
83
+ const logins: string[] = [];
84
+ for (const row of [...reviews, ...comments]) {
85
+ if (row.isBot && !logins.includes(row.author)) logins.push(row.author);
86
+ }
87
+ return logins.map((login) => {
88
+ const own = reviews.filter((review) => review.isBot && review.author === login);
89
+ const said = comments.filter((comment) => comment.isBot && comment.author === login);
90
+ // Issue comments only: a submitted review is the bot having reviewed, whatever it says.
91
+ const spoken: readonly Spoken[] = said.map((comment) => ({
92
+ at: comment.updatedAt,
93
+ url: comment.url,
94
+ notice: botNotice(comment.body),
95
+ }));
96
+ const lastReview = newest(own.map((review) => ({ at: review.submittedAt ?? '' })));
97
+ const latest = newest(spoken.filter((entry) => entry.notice !== null));
98
+ const notice =
99
+ latest?.notice == null ? null : { ...latest.notice, at: latest.at, url: latest.url };
100
+ return {
101
+ login,
102
+ reviews: own.length,
103
+ comments: said.length,
104
+ lastReviewAt: lastReview?.at ?? null,
105
+ notice,
106
+ blocked: notice !== null && (lastReview === null || lastReview.at <= notice.at),
107
+ };
108
+ });
109
+ }
package/src/pr-threads.ts CHANGED
@@ -1,12 +1,14 @@
1
1
  // The GraphQL a review lives behind, and the rows it becomes. `gh pr view --comments` shows ISSUE
2
2
  // comments; the findings a reviewer anchored to a line are `reviewThreads`, and the thread id that
3
3
  // resolves one exists in no REST response and in no web URL — this file is where that query stops
4
- // being folklore.
4
+ // being folklore. Reviews and issue comments ride the same document (`pr-activity.ts`).
5
5
 
6
6
  import { t } from '@ultimat3/schema';
7
7
  import type { GhHost } from './gh';
8
8
  import { GhResponseInvalidError, ghGraphql } from './gh';
9
9
  import type { GhRepo } from './gh-target';
10
+ import type { PrActivity } from './pr-activity';
11
+ import { ACTIVITY_FIELDS, ACTIVITY_SCHEMA, activityOf } from './pr-activity';
10
12
 
11
13
  /**
12
14
  * How many threads one page holds. The query is built from it, so the report and the request can
@@ -28,6 +30,7 @@ export const REVIEW_QUERY =
28
30
  'pullRequest(number:$n){number url headRefOid reviewDecision ' +
29
31
  'commits(last:1){nodes{commit{oid committedDate}}} ' +
30
32
  'latestOpinionatedReviews(first:20){nodes{state submittedAt author{login} commit{oid}}} ' +
33
+ `${ACTIVITY_FIELDS} ` +
31
34
  `reviewThreads(first:${THREAD_PAGE}){pageInfo{hasNextPage} nodes{id isResolved isOutdated ` +
32
35
  `path line originalLine comments(first:${COMMENT_PAGE}){totalCount ` +
33
36
  'nodes{author{login} createdAt body}}}}}}}';
@@ -59,6 +62,7 @@ const REVIEW_RESPONSE = t.object({
59
62
  }),
60
63
  ),
61
64
  }),
65
+ ...ACTIVITY_SCHEMA,
62
66
  reviewThreads: t.object({
63
67
  pageInfo: t.object({ hasNextPage: t.boolean }),
64
68
  nodes: t.array(
@@ -118,7 +122,7 @@ export interface PrReview {
118
122
  readonly stale: boolean;
119
123
  }
120
124
 
121
- export interface PrReviewReport {
125
+ export interface PrReviewReport extends PrActivity {
122
126
  readonly repo: string;
123
127
  readonly number: number;
124
128
  readonly url: string;
@@ -201,6 +205,7 @@ export async function fetchReviewReport(
201
205
  headCommittedAt: head?.committedDate ?? null,
202
206
  reviewDecision: pull.reviewDecision,
203
207
  decidingReview: decidingReview(reviews, pull.reviewDecision),
208
+ ...activityOf(pull, pull.headRefOid),
204
209
  truncated: pull.reviewThreads.pageInfo.hasNextPage,
205
210
  threads: orderThreads(
206
211
  pull.reviewThreads.nodes.map((thread) => ({
package/src/prerender.ts CHANGED
@@ -265,7 +265,7 @@ export async function prerenderSite(options: PrerenderOptions): Promise<Prerende
265
265
  // and no server is listening during a build. `renderStatic` keeps `ctx`: its output is a
266
266
  // published file, and a `site/` load a policy refuses must fail the build, never render another
267
267
  // actor's rows into it. `published` authenticates nobody: sitemap and llms.txt reads run in it.
268
- const measure = await measureScope({ origin, buildId });
268
+ const measure = await measureScope({ origin, buildId, root: options.root });
269
269
  const published = publicScope({ origin, buildId });
270
270
  // Started on the first route that needs weighing, and released however the loop ends.
271
271
  const database = measureDatabase(options.root);
@@ -436,7 +436,7 @@ export async function prerenderSite(options: PrerenderOptions): Promise<Prerende
436
436
  }));
437
437
  } finally {
438
438
  capture.close();
439
- await database.close();
439
+ await Promise.all([database.close(), measure.close()]);
440
440
  }
441
441
  // The variants and cards the exported documents name, before the worker precaches them.
442
442
  await capture.write(pages);