co-maintainer 0.6.13 → 0.7.0-beta.1

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 (156) hide show
  1. package/README.md +1 -1
  2. package/dist/package.json +1 -1
  3. package/dist/src/ai/anthropic.js +2 -0
  4. package/dist/src/ai/batch.d.ts +3 -1
  5. package/dist/src/ai/batch.js +23 -2
  6. package/dist/src/ai/mermaid_loop.js +1 -1
  7. package/dist/src/ai/oauth/sign-in-with-chatgpt.js +8 -10
  8. package/dist/src/ai/openai.js +2 -0
  9. package/dist/src/ai/openrouter.js +2 -0
  10. package/dist/src/cli/args.js +47 -0
  11. package/dist/src/cli/command_json.d.ts +20 -1
  12. package/dist/src/cli/command_json.js +4 -0
  13. package/dist/src/cli/commands/config.d.ts +1 -1
  14. package/dist/src/cli/commands/config.js +1 -0
  15. package/dist/src/cli/commands/registry.js +226 -1
  16. package/dist/src/cli/commands/review.js +50 -9
  17. package/dist/src/cli/commands/serve.js +5 -0
  18. package/dist/src/cli/commands/set.js +70 -2
  19. package/dist/src/cli/commands/view.js +46 -5
  20. package/dist/src/cli/commands/view_sources.d.ts +11 -0
  21. package/dist/src/cli/commands/view_sources.js +40 -0
  22. package/dist/src/cli/main.js +5 -0
  23. package/dist/src/cli/pr_carry.d.ts +25 -0
  24. package/dist/src/cli/pr_carry.js +128 -0
  25. package/dist/src/cli/prompt.js +26 -1
  26. package/dist/src/cli/review_args.d.ts +8 -0
  27. package/dist/src/cli/review_args.js +18 -0
  28. package/dist/src/cli/review_carry.d.ts +32 -0
  29. package/dist/src/cli/review_carry.js +60 -0
  30. package/dist/src/cli/review_github.d.ts +16 -2
  31. package/dist/src/cli/review_github.js +49 -12
  32. package/dist/src/cli/review_intent.d.ts +25 -0
  33. package/dist/src/cli/review_intent.js +87 -0
  34. package/dist/src/cli/review_result.d.ts +53 -2
  35. package/dist/src/cli/review_result.js +90 -23
  36. package/dist/src/config.d.ts +27 -0
  37. package/dist/src/config.js +20 -12
  38. package/dist/src/extensions/command.d.ts +1 -0
  39. package/dist/src/extensions/command.js +355 -0
  40. package/dist/src/extensions/contexts.d.ts +65 -0
  41. package/dist/src/extensions/contexts.js +134 -0
  42. package/dist/src/extensions/cost.d.ts +8 -0
  43. package/dist/src/extensions/cost.js +6 -0
  44. package/dist/src/extensions/local_tracking.d.ts +7 -0
  45. package/dist/src/extensions/local_tracking.js +29 -0
  46. package/dist/src/extensions/mock.d.ts +29 -0
  47. package/dist/src/extensions/mock.js +67 -0
  48. package/dist/src/extensions/process.d.ts +43 -0
  49. package/dist/src/extensions/process.js +244 -0
  50. package/dist/src/extensions/registry.d.ts +79 -0
  51. package/dist/src/extensions/registry.js +240 -0
  52. package/dist/src/extensions/render_actions.d.ts +6 -0
  53. package/dist/src/extensions/render_actions.js +50 -0
  54. package/dist/src/extensions/render_cli.d.ts +18 -0
  55. package/dist/src/extensions/render_cli.js +88 -0
  56. package/dist/src/extensions/render_json.d.ts +51 -0
  57. package/dist/src/extensions/render_json.js +144 -0
  58. package/dist/src/extensions/render_markdown.d.ts +22 -0
  59. package/dist/src/extensions/render_markdown.js +96 -0
  60. package/dist/src/extensions/render_review.d.ts +44 -0
  61. package/dist/src/extensions/render_review.js +167 -0
  62. package/dist/src/extensions/report.d.ts +57 -0
  63. package/dist/src/extensions/report.js +97 -0
  64. package/dist/src/extensions/review_result.d.ts +2 -0
  65. package/dist/src/extensions/review_result.js +14 -0
  66. package/dist/src/extensions/run_folder.d.ts +74 -0
  67. package/dist/src/extensions/run_folder.js +172 -0
  68. package/dist/src/extensions/runner.d.ts +66 -0
  69. package/dist/src/extensions/runner.js +251 -0
  70. package/dist/src/extensions/schema.d.ts +103 -0
  71. package/dist/src/extensions/schema.js +539 -0
  72. package/dist/src/extensions/session.d.ts +56 -0
  73. package/dist/src/extensions/session.js +173 -0
  74. package/dist/src/github/collect.d.ts +7 -2
  75. package/dist/src/github/collect.js +66 -6
  76. package/dist/src/github/gh.d.ts +7 -0
  77. package/dist/src/github/gh.js +24 -29
  78. package/dist/src/knowledge/guide.js +3 -2
  79. package/dist/src/knowledge/instruction_files.d.ts +45 -0
  80. package/dist/src/knowledge/instruction_files.js +91 -0
  81. package/dist/src/knowledge/instructions.d.ts +78 -0
  82. package/dist/src/knowledge/instructions.js +280 -0
  83. package/dist/src/knowledge/rule_changes.d.ts +39 -0
  84. package/dist/src/knowledge/rule_changes.js +90 -0
  85. package/dist/src/knowledge/rules.d.ts +44 -0
  86. package/dist/src/knowledge/rules.js +82 -0
  87. package/dist/src/knowledge/synthesis.d.ts +1 -0
  88. package/dist/src/knowledge/synthesis.js +12 -5
  89. package/dist/src/knowledge/types.d.ts +4 -0
  90. package/dist/src/local/carry_over_store.d.ts +10 -0
  91. package/dist/src/local/carry_over_store.js +17 -0
  92. package/dist/src/local/review_local.js +100 -62
  93. package/dist/src/local/review_lock.js +15 -4
  94. package/dist/src/pr/diff_plan.d.ts +110 -0
  95. package/dist/src/pr/diff_plan.js +429 -0
  96. package/dist/src/pr/diff_summary.d.ts +17 -1
  97. package/dist/src/pr/diff_summary.js +87 -13
  98. package/dist/src/pr/review_diff.d.ts +47 -0
  99. package/dist/src/pr/review_diff.js +112 -0
  100. package/dist/src/pr/reviewer.d.ts +44 -19
  101. package/dist/src/pr/reviewer.js +114 -142
  102. package/dist/src/remote/client.js +67 -8
  103. package/dist/src/remote/http.d.ts +12 -0
  104. package/dist/src/remote/http.js +31 -0
  105. package/dist/src/remote/push_client.js +14 -3
  106. package/dist/src/remote/server/guides.js +12 -1
  107. package/dist/src/remote/server/routes.js +4 -2
  108. package/dist/src/remote/server/sessions.js +4 -1
  109. package/dist/src/remote/validate.js +11 -0
  110. package/dist/src/review/carry_over.d.ts +6 -1
  111. package/dist/src/review/carry_over.js +10 -2
  112. package/dist/src/review/coverage.d.ts +57 -0
  113. package/dist/src/review/coverage.js +186 -0
  114. package/dist/src/review/diagram.d.ts +73 -0
  115. package/dist/src/review/diagram.js +309 -0
  116. package/dist/src/review/engine.d.ts +2 -6
  117. package/dist/src/review/engine.js +1 -1
  118. package/dist/src/review/guides.d.ts +6 -0
  119. package/dist/src/review/guides.js +8 -1
  120. package/dist/src/review/intent.d.ts +24 -0
  121. package/dist/src/review/intent.js +28 -0
  122. package/dist/src/review/not_initialized.d.ts +13 -0
  123. package/dist/src/review/not_initialized.js +18 -0
  124. package/dist/src/review/system_prompt.d.ts +6 -0
  125. package/dist/src/review/system_prompt.js +13 -0
  126. package/dist/src/review/visible_paths.d.ts +22 -0
  127. package/dist/src/review/visible_paths.js +41 -0
  128. package/dist/src/server/pages/extensions.d.ts +5 -0
  129. package/dist/src/server/pages/extensions.js +72 -0
  130. package/dist/src/server/pages/pr.js +3 -2
  131. package/dist/src/services/dashboard.d.ts +8 -0
  132. package/dist/src/services/dashboard.js +8 -0
  133. package/dist/src/services/push_review.js +14 -5
  134. package/dist/src/services/remote_review.js +81 -26
  135. package/dist/src/services/replies.js +15 -8
  136. package/dist/src/services/review.d.ts +9 -3
  137. package/dist/src/services/review.js +109 -28
  138. package/dist/src/services/rules_build.d.ts +46 -0
  139. package/dist/src/services/rules_build.js +155 -0
  140. package/dist/src/services/setup.d.ts +31 -0
  141. package/dist/src/services/setup.js +120 -25
  142. package/dist/src/services/watch_comments.js +2 -0
  143. package/dist/src/store/cache_db.js +3 -0
  144. package/dist/src/store/extensions.d.ts +51 -0
  145. package/dist/src/store/extensions.js +132 -0
  146. package/dist/src/store/migrations.js +40 -0
  147. package/dist/src/types.d.ts +22 -1
  148. package/dist/src/util/atomic.d.ts +15 -1
  149. package/dist/src/util/atomic.js +59 -29
  150. package/dist/src/util/interrupt.d.ts +6 -0
  151. package/dist/src/util/interrupt.js +27 -0
  152. package/dist/src/util/runtime.d.ts +3 -1
  153. package/dist/src/util/runtime.js +2 -2
  154. package/dist/src/util/test_location_guard.d.ts +6 -0
  155. package/dist/src/util/test_location_guard.js +47 -0
  156. package/package.json +1 -1
@@ -1,8 +1,10 @@
1
1
  import { VERSION } from "../version.js";
2
- import { loadReviewSystemPromptFlags } from "../cli/review_args.js";
2
+ import { loadReviewSystemPromptFlags, reviewSystemPromptLimitFor, } from "../cli/review_args.js";
3
+ import { intentRecord, loadIntentFlag } from "../cli/review_intent.js";
3
4
  import { exitWith } from "../cli/error.js";
4
5
  import { formatHumanReview, humanFindingsFromJson, reviewExitCodeFromJsonFindings, } from "../cli/review_result.js";
5
- import { baseUrl, die, readApiError, remoteFetch, remoteFromEnv, } from "./http.js";
6
+ import { coverageFromResult, warningsFromJson } from "../review/coverage.js";
7
+ import { baseUrl, die, handshakeFailure, readApiError, remoteFetch, remoteFromEnv, } from "./http.js";
6
8
  import { readConfig, writeUserConfig } from "../config.js";
7
9
  import { getEnv } from "../util/runtime.js";
8
10
  import { stripControlChars } from "../util/sanitize.js";
@@ -18,7 +20,16 @@ import { printRunSummary } from "../util/run_summary.js";
18
20
  import { emitGithubOutput, neutralizeCommands } from "../cli/review_github.js";
19
21
  import { costReasonText } from "../util/cost.js";
20
22
  import { setCliInteractive } from "../cli/args.js";
23
+ import { splitRemoteResult, stripExtensionMarkdowns, } from "../extensions/render_json.js";
24
+ import { exitCodeWithExtensions } from "../extensions/report.js";
21
25
  import { MIN_SERVER_SCHEMA, REMOTE_CLI_UPGRADE_COMMAND, REMOTE_SCHEMA_VERSION, } from "./schema.js";
26
+ /** The subject of a server's result without an `intent` of its own. */
27
+ function withoutIntent(subject) {
28
+ if (typeof subject !== "object" || subject === null)
29
+ return {};
30
+ const { intent: _intent, ...rest } = subject;
31
+ return rest;
32
+ }
22
33
  const LOCAL_BYOK_HOSTNAMES = new Set(["localhost", "127.0.0.1", "::1"]);
23
34
  /** A plain-http, non-local host means the BYOK key travels in the clear.
24
35
  * Pulled out as a pure function so the rule is unit-testable
@@ -58,6 +69,7 @@ export async function runRemoteReview(cli) {
58
69
  await assertGitQuiet(root);
59
70
  const repo = await detectRemoteRepo(root, cli.repoOverride);
60
71
  const branch = await currentBranch(root, cli.branch);
72
+ const intentLoad = await loadIntentFlag(cli.intentFile, reviewSystemPromptLimitFor(repo));
61
73
  const remotes = await runCommand("git", ["remote"], root);
62
74
  const remoteName = ["upstream", "origin"].find((n) => remotes.stdout
63
75
  .split("\n")
@@ -83,6 +95,10 @@ export async function runRemoteReview(cli) {
83
95
  console.log("No changes to review.");
84
96
  }
85
97
  exitWith(0);
98
+ // `exitWith` only sets the exit code. Without this return the client
99
+ // went on to submit an empty change, the server refused it, and the
100
+ // run ended with exit 2 after saying there was nothing to review.
101
+ return;
86
102
  }
87
103
  const handshake = await remoteFetch(host, token, "/api/remote/handshake", {
88
104
  method: "POST",
@@ -93,7 +109,7 @@ export async function runRemoteReview(cli) {
93
109
  }),
94
110
  });
95
111
  if (!handshake.ok) {
96
- die("remote_handshake_failed", await readApiError(handshake));
112
+ throw await handshakeFailure(handshake, host, repo);
97
113
  }
98
114
  const hs = (await handshake.json());
99
115
  if (REMOTE_SCHEMA_VERSION < hs.minClientSchema) {
@@ -115,6 +131,17 @@ export async function runRemoteReview(cli) {
115
131
  if (serverSupportsByok && hs.byok?.policy === "require" && !byokEnabled) {
116
132
  die("remote_byok_required", "This server requires your own key.", "co-maintainer review --remote --remote-byok");
117
133
  }
134
+ // A server that predates intent would never use the text, so it is not
135
+ // sent, and the run says it went without.
136
+ const serverSupportsIntent = hs.features?.includes("intent") ?? false;
137
+ const intent = serverSupportsIntent ? intentLoad.intent : null;
138
+ const clientWarnings = [...intentLoad.warnings];
139
+ if (intentLoad.intent && !serverSupportsIntent) {
140
+ clientWarnings.push({
141
+ code: "intent_unsupported",
142
+ message: `This server (version ${hs.serverVersion}) does not support an intent, so the review ran without one.`,
143
+ });
144
+ }
118
145
  if (byokEnabled && !cli.json) {
119
146
  const warning = byokHttpWarning(host);
120
147
  if (warning)
@@ -156,7 +183,7 @@ export async function runRemoteReview(cli) {
156
183
  fresh: cli.fresh,
157
184
  revision: {
158
185
  title: built.revision.title,
159
- description: built.revision.description,
186
+ description: intent?.text ?? built.revision.description,
160
187
  baseLabel: built.revision.baseLabel,
161
188
  files: built.revision.files,
162
189
  },
@@ -182,7 +209,11 @@ export async function runRemoteReview(cli) {
182
209
  body: serialized,
183
210
  });
184
211
  if (submit.status !== 202) {
185
- die("remote_submit_failed", await readApiError(submit));
212
+ const why = await readApiError(submit);
213
+ // The user typed the flag, so a refusal of the text names it.
214
+ die("remote_submit_failed", intent && /revision\.description/.test(why)
215
+ ? `--intent-file was refused by the server: ${why}`
216
+ : why);
186
217
  }
187
218
  const { jobId } = (await submit.json());
188
219
  let afterLogSeq = 0;
@@ -223,7 +254,8 @@ export async function runRemoteReview(cli) {
223
254
  continue;
224
255
  }
225
256
  if (payload.status === "done" && payload.result) {
226
- const findings = (payload.result.findings ?? []);
257
+ const { aiFindings, report: extensions } = splitRemoteResult(payload.result);
258
+ const findings = aiFindings;
227
259
  const usage = payload.result.usage;
228
260
  const known = usage !== undefined &&
229
261
  usage.costUsd !== null &&
@@ -244,7 +276,21 @@ export async function runRemoteReview(cli) {
244
276
  schemaVersion: 1,
245
277
  ok: true,
246
278
  mode: "remote",
247
- ...payload.result,
279
+ ...stripExtensionMarkdowns(payload.result, cli.includeExtensionMarkdowns ?? false),
280
+ // The client knows how the intent came in, so a server cannot
281
+ // say otherwise.
282
+ subject: {
283
+ ...withoutIntent(payload.result.subject),
284
+ ...(intent ? { intent: intentRecord(intent) } : {}),
285
+ },
286
+ ...(clientWarnings.length > 0
287
+ ? {
288
+ warnings: [
289
+ ...warningsFromJson(payload.result.warnings),
290
+ ...clientWarnings,
291
+ ],
292
+ }
293
+ : {}),
248
294
  }));
249
295
  }
250
296
  else if (cli.output === "github") {
@@ -252,6 +298,12 @@ export async function runRemoteReview(cli) {
252
298
  title: `${repo} · ${branch} (remote)`,
253
299
  findings: humanFindingsFromJson(findings),
254
300
  run,
301
+ coverage: coverageFromResult(payload.result),
302
+ // The server keeps this branch's carry-over, so its next run
303
+ // sends the files this one dropped.
304
+ catchesUp: true,
305
+ extensions,
306
+ intent: intent !== null,
255
307
  });
256
308
  }
257
309
  else {
@@ -263,12 +315,19 @@ export async function runRemoteReview(cli) {
263
315
  guideBuiltAt: resultGuide?.builtAt ?? null,
264
316
  codegraphState: resultCodegraph?.state ?? null,
265
317
  findings: humanFindingsFromJson(findings),
318
+ warnings: [
319
+ ...warningsFromJson(payload.result.warnings),
320
+ ...clientWarnings,
321
+ ],
322
+ coverage: coverageFromResult(payload.result),
323
+ extensions,
324
+ intent: intent !== null,
266
325
  }) +
267
326
  "\n");
268
327
  if (run)
269
328
  printRunSummary(run);
270
329
  }
271
- exitWith(reviewExitCodeFromJsonFindings(findings));
330
+ exitWith(exitCodeWithExtensions(reviewExitCodeFromJsonFindings((payload.result.findings ?? [])), extensions));
272
331
  // `done` is terminal. Without this return the loop polls `sync` again
273
332
  // and, since the server keeps reporting the same finished job, the
274
333
  // client reprints the result and re-requests forever.
@@ -1,3 +1,10 @@
1
+ /** Shared HTTPS plumbing for the remote endpoints.
2
+ *
3
+ * `review --remote` and `view --remote` talk to the same server with the same
4
+ * bearer token, so the base URL, the token header and the explanations for a
5
+ * rejected token or an unreachable host live here rather than in the review
6
+ * client alone. */
7
+ import { CliError } from "../cli/error.ts";
1
8
  /** Where the remote server is, as an environment variable can say it.
2
9
  * A CI job has no config file, and a token on the command line
3
10
  * ends up in the process list, so `CM_REMOTE_HOST` and `CM_REMOTE_TOKEN` are
@@ -12,3 +19,8 @@ export declare function die(code: string, message: string, hint?: string, exitCo
12
19
  export declare function baseUrl(host: string): string;
13
20
  export declare function remoteFetch(host: string, token: string, path: string, init: RequestInit): Promise<Response>;
14
21
  export declare function readApiError(response: Response): Promise<string>;
22
+ /** The handshake was refused. A repository without guides and a repository the
23
+ * server does not know are different problems with different fixes, and every
24
+ * server so far sends them as different codes. Anything else, including a
25
+ * refusal with no code, stays a handshake failure. */
26
+ export declare function handshakeFailure(response: Response, host: string, repo: string): Promise<CliError>;
@@ -5,7 +5,9 @@
5
5
  * rejected token or an unreachable host live here rather than in the review
6
6
  * client alone. */
7
7
  import { CliError, EXIT_USAGE, networkFailure } from "../cli/error.js";
8
+ import { NOT_INITIALIZED, notInitializedError, } from "../review/not_initialized.js";
8
9
  import { getEnv } from "../util/runtime.js";
10
+ import { stripControlChars } from "../util/sanitize.js";
9
11
  /** Where the remote server is, as an environment variable can say it.
10
12
  * A CI job has no config file, and a token on the command line
11
13
  * ends up in the process list, so `CM_REMOTE_HOST` and `CM_REMOTE_TOKEN` are
@@ -59,3 +61,32 @@ export async function readApiError(response) {
59
61
  return response.statusText;
60
62
  }
61
63
  }
64
+ /** The server's error code and message. The code is how a client tells one
65
+ * refusal from another, and an old server or a proxy may send none. */
66
+ async function readApiErrorBody(response) {
67
+ try {
68
+ const body = await response.json();
69
+ return {
70
+ code: typeof body.error?.code === "string" ? body.error.code : undefined,
71
+ message: String(body.error?.message ?? response.statusText),
72
+ };
73
+ }
74
+ catch {
75
+ return { message: response.statusText };
76
+ }
77
+ }
78
+ /** The handshake was refused. A repository without guides and a repository the
79
+ * server does not know are different problems with different fixes, and every
80
+ * server so far sends them as different codes. Anything else, including a
81
+ * refusal with no code, stays a handshake failure. */
82
+ export async function handshakeFailure(response, host, repo) {
83
+ const { code, message } = await readApiErrorBody(response);
84
+ const serverHost = new URL(baseUrl(host)).host;
85
+ if (code === NOT_INITIALIZED)
86
+ return notInitializedError(repo, serverHost);
87
+ if (code === "repo_unavailable") {
88
+ return new CliError("repo_unavailable", `The server at ${serverHost} does not have ${repo} available for review.`, "Check the owner/repo name, or add the repository on that server first.", EXIT_USAGE);
89
+ }
90
+ // The text is the server's own, and it reaches a terminal or a CI log.
91
+ return new CliError("remote_handshake_failed", stripControlChars(message), undefined, EXIT_USAGE);
92
+ }
@@ -14,7 +14,9 @@
14
14
  import { VERSION } from "../version.js";
15
15
  import { exitWith } from "../cli/error.js";
16
16
  import { formatHumanReview, humanFindingsFromJson, } from "../cli/review_result.js";
17
- import { baseUrl, die, readApiError, remoteFetch, remoteFromEnv, } from "./http.js";
17
+ import { coverageFromResult, warningsFromJson } from "../review/coverage.js";
18
+ import { baseUrl, die, handshakeFailure, readApiError, remoteFetch, remoteFromEnv, } from "./http.js";
19
+ import { notInitializedError } from "../review/not_initialized.js";
18
20
  import { readConfig } from "../config.js";
19
21
  import { stripControlChars } from "../util/sanitize.js";
20
22
  import { runCommand } from "../pr/checkout.js";
@@ -139,7 +141,7 @@ export async function runRemotePushReview(cli) {
139
141
  }),
140
142
  });
141
143
  if (!handshake.ok)
142
- die("remote_handshake_failed", await readApiError(handshake));
144
+ throw await handshakeFailure(handshake, host, repo);
143
145
  const hs = (await handshake.json());
144
146
  if (REMOTE_SCHEMA_VERSION < hs.minClientSchema) {
145
147
  die("upgrade_required", "This co-maintainer CLI is too old for the server.", REMOTE_CLI_UPGRADE_COMMAND, 4);
@@ -205,6 +207,9 @@ export async function runRemotePushReview(cli) {
205
207
  exitWith(0);
206
208
  return;
207
209
  }
210
+ if (error.code === "not_initialized") {
211
+ throw notInitializedError(repo, new URL(baseUrl(host)).host);
212
+ }
208
213
  die(error.code ?? "remote_submit_failed", error.message ?? "The server refused the push.");
209
214
  }
210
215
  if (!submitted)
@@ -253,7 +258,11 @@ export async function runRemotePushReview(cli) {
253
258
  }));
254
259
  }
255
260
  else if (cli.output === "github") {
256
- emitGithubOutput({ title, findings: human });
261
+ emitGithubOutput({
262
+ title,
263
+ findings: human,
264
+ coverage: coverageFromResult(payload.result),
265
+ });
257
266
  }
258
267
  else {
259
268
  console.log("\n" +
@@ -262,6 +271,8 @@ export async function runRemotePushReview(cli) {
262
271
  guideBuiltAt: null,
263
272
  codegraphState: null,
264
273
  findings: human,
274
+ warnings: warningsFromJson(payload.result.warnings),
275
+ coverage: coverageFromResult(payload.result),
265
276
  }) +
266
277
  "\n");
267
278
  }
@@ -9,14 +9,19 @@
9
9
  * per file. */
10
10
  import { reposDir } from "../../config.js";
11
11
  import { loadGuides } from "../../review/guides.js";
12
+ import { rulesFileText } from "../../knowledge/rules.js";
12
13
  import { readDir, readTextFile, stat } from "../../util/runtime.js";
13
14
  import { validateRemotePath } from "../validate.js";
14
- /** The four generated guides, in the order a reader wants them. */
15
+ /** The generated guides, in the order a reader wants them. `RULES.json`
16
+ * comes back too, with kind `rules`, so `view --remote --sources` needs no
17
+ * second endpoint. */
15
18
  const GUIDES = [
16
19
  { kind: "skill", file: "SKILL.md" },
17
20
  { kind: "codebase", file: "CODEBASE.md" },
18
21
  { kind: "review-guide", file: "PR_REVIEW_GUIDE.md" },
19
22
  { kind: "detailed-guide", file: "PR_REVIEW_DETAILED_GUIDE.md" },
23
+ { kind: "instructions", file: "INSTRUCTIONS.md" },
24
+ { kind: "rules", file: "RULES.json" },
20
25
  ];
21
26
  /** Canonicalizes `owner/repo` from the query string. A value that escapes is
22
27
  * refused before any directory is touched, the same guard the revision payload
@@ -42,6 +47,12 @@ export async function readRemoteGuides(repo) {
42
47
  ["PR_REVIEW_DETAILED_GUIDE.md", loaded.detailed],
43
48
  ["CODEBASE.md", loaded.codebase],
44
49
  ["SKILL.md", loaded.skill],
50
+ ["INSTRUCTIONS.md", loaded.instructions],
51
+ // From the read under the lock, so it belongs to the same build as the
52
+ // guides served with it.
53
+ ...(loaded.rules
54
+ ? [["RULES.json", rulesFileText(loaded.rules)]]
55
+ : []),
45
56
  ]);
46
57
  const dir = `${reposDir()}/${repo}`;
47
58
  const names = [];
@@ -76,7 +76,9 @@ async function handleHandshake(request, ip) {
76
76
  // A push review decides about a repository with no guides itself, so the
77
77
  // commit can get a skipped check run when the App covers it.
78
78
  if (!guides.shortGuide && !guides.skill && record.purpose !== "push") {
79
- return errorResponse(409, "not_initialized", REPO_UNAVAILABLE);
79
+ // The status and the code stay as they were so an older client still
80
+ // reads this as a refusal. Only the text says what is missing.
81
+ return errorResponse(409, "not_initialized", `Review guides are missing for ${repoRow.full_name} on this server.`);
80
82
  }
81
83
  const config = readConfig();
82
84
  const timeoutSeconds = config.remoteSyncTimeoutSeconds ?? 10;
@@ -103,7 +105,7 @@ async function handleHandshake(request, ip) {
103
105
  // Additive advertisement: a 0.5.0 client ignores these, and an
104
106
  // older server never sends them, so the client gates on `features`. No key,
105
107
  // model, or other secret is ever echoed here.
106
- features: ["byok", "push"],
108
+ features: ["byok", "push", "intent"],
107
109
  byok: { policy },
108
110
  ai: { provider: config.ai ?? "openrouter" },
109
111
  });
@@ -18,7 +18,10 @@ export function getRemoteSession(jobId) {
18
18
  export function closeRemoteSession(jobId) {
19
19
  sessions.delete(jobId);
20
20
  clearRemoteToolBridge(jobId);
21
- setTimeout(() => finishedResults.delete(jobId), 60_000);
21
+ // A cleanup timer must not keep the process alive: a process that runs the
22
+ // remote routes without `serve` (a test, e2e:simulate) would wait a minute
23
+ // after its last review before it could exit.
24
+ setTimeout(() => finishedResults.delete(jobId), 60_000).unref();
22
25
  }
23
26
  export function setRemoteSyncResult(jobId, result) {
24
27
  finishedResults.set(jobId, result);
@@ -118,6 +118,17 @@ export function validateRevisionPayload(revision) {
118
118
  if (!Array.isArray(files) || files.length < 1) {
119
119
  return bad("revision.files", "must have at least one file");
120
120
  }
121
+ // The description carries a client's intent. The repository's own cap is
122
+ // applied when the review is submitted, this is the ceiling before it.
123
+ const description = revision.description;
124
+ if (description !== undefined) {
125
+ if (typeof description !== "string") {
126
+ return bad("revision.description", "must be a string");
127
+ }
128
+ if (description.length > REMOTE_MAX_SYSTEM_PROMPT_CHARS) {
129
+ return bad("revision.description", "too long");
130
+ }
131
+ }
121
132
  const paths = new Set();
122
133
  for (let i = 0; i < files.length; i++) {
123
134
  const err = validateRevisionFile(files[i], i, paths);
@@ -70,7 +70,12 @@ export type PreviousVerdict = {
70
70
  export declare function parsePreviousVerdicts(markdown: string): PreviousVerdict[];
71
71
  export declare function findingsMarkdownForParse(markdown: string): string;
72
72
  export declare function resolveCarryOutcomes(items: CarryItem[], current: Revision, visiblePaths: Set<string>, verdicts: PreviousVerdict[], parsedNew: ParsedFinding[]): ResolvedFinding[];
73
- export declare function incrementalDiffPaths(current: Revision, previousFiles: RevisionFile[] | null): {
73
+ /** Splits the current files into the ones to send and the ones an earlier
74
+ * round already covered. A file counts as unchanged only when its patch is
75
+ * the same as last round's and it is in last round's seen set: a file that
76
+ * was dropped or withheld then never reached the model, so it is sent again
77
+ * however little it changed. */
78
+ export declare function incrementalDiffPaths(current: Revision, previousFiles: RevisionFile[] | null, seenPaths: Set<string>): {
74
79
  changed: RevisionFile[];
75
80
  unchanged: string[];
76
81
  };
@@ -385,16 +385,24 @@ export function resolveCarryOutcomes(items, current, visiblePaths, verdicts, par
385
385
  }
386
386
  return resolved;
387
387
  }
388
- export function incrementalDiffPaths(current, previousFiles) {
388
+ /** Splits the current files into the ones to send and the ones an earlier
389
+ * round already covered. A file counts as unchanged only when its patch is
390
+ * the same as last round's and it is in last round's seen set: a file that
391
+ * was dropped or withheld then never reached the model, so it is sent again
392
+ * however little it changed. */
393
+ export function incrementalDiffPaths(current, previousFiles, seenPaths) {
389
394
  if (!previousFiles) {
390
395
  return { changed: current.files, unchanged: [] };
391
396
  }
392
397
  const prevByPath = new Map(previousFiles.map((file) => [normalizePath(file.path), file]));
398
+ const seen = new Set([...seenPaths].map(normalizePath));
393
399
  const changed = [];
394
400
  const unchanged = [];
395
401
  for (const file of current.files) {
396
402
  const prev = prevByPath.get(normalizePath(file.path));
397
- if (!prev || !revisionFilesEquivalent(prev, file)) {
403
+ if (!prev ||
404
+ !revisionFilesEquivalent(prev, file) ||
405
+ !seen.has(normalizePath(file.path))) {
398
406
  changed.push(file);
399
407
  }
400
408
  else {
@@ -0,0 +1,57 @@
1
+ /** `full` is a count, every other state names its files. */
2
+ export type Coverage = {
3
+ full: number;
4
+ partial: string[];
5
+ summarized: string[];
6
+ dropped: string[];
7
+ withheld: string[];
8
+ };
9
+ export type CoverageWarning = {
10
+ code: string;
11
+ message: string;
12
+ };
13
+ /** A review that never ran a diff plan, such as a push with no changed files,
14
+ * saw every one of its files in full. */
15
+ export declare function fullCoverage(files: number): Coverage;
16
+ /** True when any file reached the model as less than its whole patch. */
17
+ export declare function coverageTruncated(coverage: Coverage): boolean;
18
+ /** Files the model never received at all. Findings can only speak for the
19
+ * other files. */
20
+ export declare function coverageMissing(coverage: Coverage): number;
21
+ /** `58 full · 1 partial · 3 summarized · 0 dropped`, with the withheld count
22
+ * only when there is one, since only a pull request review can have it. */
23
+ export declare function coverageCounts(coverage: Coverage): string;
24
+ /** The terminal's coverage line, or `null` when every file was full. */
25
+ export declare function coverageLine(coverage: Coverage | undefined): string | null;
26
+ /** The warnings a diff plan leaves behind, in the order a reader needs them:
27
+ * what was not reviewed first, then what was reviewed from less text than
28
+ * planned.
29
+ *
30
+ * `catchesUp` is the caller's word that its next run leaves out the files
31
+ * this one saw, so it sends the dropped ones. Only then does the warning
32
+ * promise a later round. A mode without carry-over drops the same files on
33
+ * every run, and the warning says so instead. */
34
+ export declare function coverageWarnings(coverage: Coverage, catchesUp: boolean, summaryFailed?: string[]): CoverageWarning[];
35
+ /** At most this many files are named in a not-reviewed list. */
36
+ export declare const NOT_REVIEWED_LIST_LIMIT = 20;
37
+ /** The `Not reviewed (N)` list for a GitHub review or a job summary, empty
38
+ * when every file reached the model. `catchesUp` is the same promise as in
39
+ * `coverageWarnings`. `formatPath` lets each caller escape a path for where
40
+ * it lands. */
41
+ export declare function notReviewedLines(coverage: Coverage | undefined, catchesUp: boolean, formatPath?: (path: string) => string): string[];
42
+ /** A file path as an inline code span in a body co-maintainer posts to GitHub.
43
+ * The pull request's author chooses file names, so a name must not end the
44
+ * span, start a heading or a link, or mention someone. Control characters and
45
+ * line breaks go. A backtick becomes the look-alike `ˋ`, so the span stays the
46
+ * plain one-backtick form the copy guard in `outsideCode` recognizes. An `@`
47
+ * gets a zero-width space after it, so it can never be read as a mention. */
48
+ export declare function postedPathSpan(path: string): string;
49
+ /** A coverage block read from a remote server's result. A server older than
50
+ * this field sends none, and a malformed block is treated the same way, so
51
+ * the client never prints a claim it cannot check. */
52
+ export declare function coverageFromJson(value: unknown): Coverage | undefined;
53
+ /** The coverage inside a remote result's `revision` block. */
54
+ export declare function coverageFromResult(result: Record<string, unknown>): Coverage | undefined;
55
+ /** Warnings read from a remote server's result, with the same tolerance as
56
+ * `coverageFromJson`: an older server sends no list. */
57
+ export declare function warningsFromJson(value: unknown): CoverageWarning[];
@@ -0,0 +1,186 @@
1
+ /** What a review's model actually received, file by file, and the words every
2
+ * output uses to say so. The states come from the diff plan in
3
+ * `src/pr/diff_plan.ts`. This file only counts and words them, so the
4
+ * terminal, `--json`, `--output=github` and the GitHub review cannot drift
5
+ * into different stories about the same run. */
6
+ import { stripControlChars } from "../util/sanitize.js";
7
+ /** A review that never ran a diff plan, such as a push with no changed files,
8
+ * saw every one of its files in full. */
9
+ export function fullCoverage(files) {
10
+ return {
11
+ full: files,
12
+ partial: [],
13
+ summarized: [],
14
+ dropped: [],
15
+ withheld: [],
16
+ };
17
+ }
18
+ /** True when any file reached the model as less than its whole patch. */
19
+ export function coverageTruncated(coverage) {
20
+ return (coverage.partial.length > 0 ||
21
+ coverage.summarized.length > 0 ||
22
+ coverage.dropped.length > 0 ||
23
+ coverage.withheld.length > 0);
24
+ }
25
+ /** Files the model never received at all. Findings can only speak for the
26
+ * other files. */
27
+ export function coverageMissing(coverage) {
28
+ return coverage.dropped.length + coverage.withheld.length;
29
+ }
30
+ /** `58 full · 1 partial · 3 summarized · 0 dropped`, with the withheld count
31
+ * only when there is one, since only a pull request review can have it. */
32
+ export function coverageCounts(coverage) {
33
+ const parts = [
34
+ `${coverage.full} full`,
35
+ `${coverage.partial.length} partial`,
36
+ `${coverage.summarized.length} summarized`,
37
+ `${coverage.dropped.length} dropped`,
38
+ ];
39
+ if (coverage.withheld.length > 0) {
40
+ parts.push(`${coverage.withheld.length} withheld`);
41
+ }
42
+ return parts.join(" · ");
43
+ }
44
+ /** The terminal's coverage line, or `null` when every file was full. */
45
+ export function coverageLine(coverage) {
46
+ if (!coverage || !coverageTruncated(coverage))
47
+ return null;
48
+ return `Coverage: ${coverageCounts(coverage)}`;
49
+ }
50
+ function files(count) {
51
+ return count === 1 ? "1 file was" : `${count} files were`;
52
+ }
53
+ /** The warnings a diff plan leaves behind, in the order a reader needs them:
54
+ * what was not reviewed first, then what was reviewed from less text than
55
+ * planned.
56
+ *
57
+ * `catchesUp` is the caller's word that its next run leaves out the files
58
+ * this one saw, so it sends the dropped ones. Only then does the warning
59
+ * promise a later round. A mode without carry-over drops the same files on
60
+ * every run, and the warning says so instead. */
61
+ export function coverageWarnings(coverage, catchesUp, summaryFailed = []) {
62
+ const warnings = [];
63
+ const dropped = coverage.dropped.length;
64
+ if (dropped > 0) {
65
+ const them = dropped === 1 ? "it" : "them";
66
+ warnings.push({
67
+ code: "diff_dropped",
68
+ message: catchesUp
69
+ ? `${files(dropped)} not reviewed because the diff is too large. Run review again to cover ${them}.`
70
+ : `${files(dropped)} not reviewed because the diff is too large. This review mode does not cover ${them} in a later run.`,
71
+ });
72
+ }
73
+ const withheld = coverage.withheld.length;
74
+ if (withheld > 0) {
75
+ warnings.push({
76
+ code: "diff_withheld",
77
+ message: `${files(withheld)} not reviewed because GitHub sent no diff for ${withheld === 1 ? "it" : "them"}.`,
78
+ });
79
+ }
80
+ if (summaryFailed.length === 1) {
81
+ warnings.push({
82
+ code: "summary_failed",
83
+ message: `The summary of ${summaryFailed[0]} failed, so the review saw its diff instead, up to the first 12,000 characters.`,
84
+ });
85
+ }
86
+ else if (summaryFailed.length > 1) {
87
+ const shown = summaryFailed.slice(0, 5).join(", ");
88
+ const more = summaryFailed.length > 5 ? ` and ${summaryFailed.length - 5} more` : "";
89
+ warnings.push({
90
+ code: "summary_failed",
91
+ message: `The summaries of ${summaryFailed.length} files failed, so the review saw their diffs instead, up to the first 12,000 characters each: ${shown}${more}.`,
92
+ });
93
+ }
94
+ return warnings;
95
+ }
96
+ /** At most this many files are named in a not-reviewed list. */
97
+ export const NOT_REVIEWED_LIST_LIMIT = 20;
98
+ /** The `Not reviewed (N)` list for a GitHub review or a job summary, empty
99
+ * when every file reached the model. `catchesUp` is the same promise as in
100
+ * `coverageWarnings`. `formatPath` lets each caller escape a path for where
101
+ * it lands. */
102
+ export function notReviewedLines(coverage, catchesUp, formatPath = (path) => path) {
103
+ if (!coverage || coverageMissing(coverage) === 0)
104
+ return [];
105
+ const why = catchesUp
106
+ ? "the diff was too large for this round"
107
+ : "the diff was too large, not reviewed in this mode";
108
+ const rows = [
109
+ ...coverage.dropped.map((path) => `- ${formatPath(path)}: ${why}`),
110
+ ...coverage.withheld.map((path) => `- ${formatPath(path)}: GitHub sent no diff`),
111
+ ];
112
+ const shown = rows.slice(0, NOT_REVIEWED_LIST_LIMIT);
113
+ if (rows.length > shown.length) {
114
+ shown.push(`- and ${rows.length - shown.length} more`);
115
+ }
116
+ return [`Not reviewed (${rows.length})`, ...shown];
117
+ }
118
+ /** A file path as an inline code span in a body co-maintainer posts to GitHub.
119
+ * The pull request's author chooses file names, so a name must not end the
120
+ * span, start a heading or a link, or mention someone. Control characters and
121
+ * line breaks go. A backtick becomes the look-alike `ˋ`, so the span stays the
122
+ * plain one-backtick form the copy guard in `outsideCode` recognizes. An `@`
123
+ * gets a zero-width space after it, so it can never be read as a mention. */
124
+ export function postedPathSpan(path) {
125
+ const flat = stripControlChars(path)
126
+ .replace(/[\n\t]+/g, " ")
127
+ .replaceAll("`", MODIFIER_GRAVE)
128
+ .replaceAll("@", `@${ZERO_WIDTH_SPACE}`);
129
+ return `\`${flat}\``;
130
+ }
131
+ // Built from their codes: the formatter rewrites a `\u` escape in a string
132
+ // into the character itself, and both are invisible or look like others.
133
+ const MODIFIER_GRAVE = String.fromCharCode(0x02cb);
134
+ const ZERO_WIDTH_SPACE = String.fromCharCode(0x200b);
135
+ function pathList(value) {
136
+ if (!Array.isArray(value))
137
+ return undefined;
138
+ if (!value.every((item) => typeof item === "string"))
139
+ return undefined;
140
+ return value.map((item) => stripControlChars(item));
141
+ }
142
+ /** A coverage block read from a remote server's result. A server older than
143
+ * this field sends none, and a malformed block is treated the same way, so
144
+ * the client never prints a claim it cannot check. */
145
+ export function coverageFromJson(value) {
146
+ if (!value || typeof value !== "object")
147
+ return undefined;
148
+ const raw = value;
149
+ const full = raw.full;
150
+ if (typeof full !== "number" || !Number.isFinite(full) || full < 0) {
151
+ return undefined;
152
+ }
153
+ const partial = pathList(raw.partial);
154
+ const summarized = pathList(raw.summarized);
155
+ const dropped = pathList(raw.dropped);
156
+ const withheld = pathList(raw.withheld);
157
+ if (!partial || !summarized || !dropped || !withheld)
158
+ return undefined;
159
+ return { full, partial, summarized, dropped, withheld };
160
+ }
161
+ /** The coverage inside a remote result's `revision` block. */
162
+ export function coverageFromResult(result) {
163
+ const revision = result.revision;
164
+ if (!revision || typeof revision !== "object")
165
+ return undefined;
166
+ return coverageFromJson(revision.coverage);
167
+ }
168
+ /** Warnings read from a remote server's result, with the same tolerance as
169
+ * `coverageFromJson`: an older server sends no list. */
170
+ export function warningsFromJson(value) {
171
+ if (!Array.isArray(value))
172
+ return [];
173
+ const warnings = [];
174
+ for (const item of value) {
175
+ if (!item || typeof item !== "object")
176
+ continue;
177
+ const { code, message } = item;
178
+ if (typeof code !== "string" || typeof message !== "string")
179
+ continue;
180
+ warnings.push({
181
+ code: stripControlChars(code),
182
+ message: stripControlChars(message),
183
+ });
184
+ }
185
+ return warnings;
186
+ }