co-maintainer 0.6.8 → 0.6.10

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 (75) hide show
  1. package/dist/package.json +1 -1
  2. package/dist/src/ai/fake.d.ts +10 -1
  3. package/dist/src/ai/fake.js +39 -4
  4. package/dist/src/cli/args.js +2 -0
  5. package/dist/src/cli/command_json.d.ts +6 -0
  6. package/dist/src/cli/command_json.js +1 -0
  7. package/dist/src/cli/commands/probe.js +25 -0
  8. package/dist/src/cli/commands/registry.js +11 -0
  9. package/dist/src/cli/commands/review.js +5 -1
  10. package/dist/src/cli/commands/serve.js +10 -0
  11. package/dist/src/cli/commands/set.js +23 -2
  12. package/dist/src/cli/review_args.d.ts +9 -0
  13. package/dist/src/cli/review_args.js +36 -1
  14. package/dist/src/cli/review_github.js +6 -2
  15. package/dist/src/cli/review_result.js +6 -5
  16. package/dist/src/github/app.d.ts +4 -0
  17. package/dist/src/github/app.js +10 -1
  18. package/dist/src/github/permissions.js +40 -0
  19. package/dist/src/local/git_ops.js +3 -2
  20. package/dist/src/local/git_revision.d.ts +5 -2
  21. package/dist/src/local/git_revision.js +17 -10
  22. package/dist/src/pr/checkout.js +14 -5
  23. package/dist/src/pr/codegraph_tools.js +5 -3
  24. package/dist/src/pr/reviewer.d.ts +2 -0
  25. package/dist/src/pr/reviewer.js +1 -1
  26. package/dist/src/remote/client.js +14 -4
  27. package/dist/src/remote/push_client.d.ts +7 -0
  28. package/dist/src/remote/push_client.js +287 -0
  29. package/dist/src/remote/server/body.d.ts +11 -0
  30. package/dist/src/remote/server/body.js +14 -5
  31. package/dist/src/remote/server/routes.d.ts +1 -0
  32. package/dist/src/remote/server/routes.js +61 -4
  33. package/dist/src/remote/server/sync.js +11 -3
  34. package/dist/src/remote/validate.js +17 -0
  35. package/dist/src/server/api/repos.js +13 -2
  36. package/dist/src/server/app.js +5 -6
  37. package/dist/src/server/http.js +5 -0
  38. package/dist/src/server/pages/layout.js +1 -0
  39. package/dist/src/server/pages/repo.d.ts +3 -1
  40. package/dist/src/server/pages/repo.js +4 -1
  41. package/dist/src/server/pages/repo_pushes.d.ts +7 -0
  42. package/dist/src/server/pages/repo_pushes.js +144 -0
  43. package/dist/src/server/pages/repo_settings.js +45 -1
  44. package/dist/src/server/pages/router.js +34 -5
  45. package/dist/src/server/pages/settings.js +1 -1
  46. package/dist/src/server/webhook/index.js +24 -7
  47. package/dist/src/services/dashboard.d.ts +46 -0
  48. package/dist/src/services/dashboard.js +24 -0
  49. package/dist/src/services/jobs.js +18 -3
  50. package/dist/src/services/push_review.d.ts +51 -0
  51. package/dist/src/services/push_review.js +878 -0
  52. package/dist/src/services/setup.js +21 -0
  53. package/dist/src/services/watch_comments.d.ts +10 -0
  54. package/dist/src/services/watch_comments.js +179 -0
  55. package/dist/src/services/watch_issues.d.ts +70 -0
  56. package/dist/src/services/watch_issues.js +266 -0
  57. package/dist/src/services/watch_notes.d.ts +8 -0
  58. package/dist/src/services/watch_notes.js +80 -0
  59. package/dist/src/services/watch_status.d.ts +25 -0
  60. package/dist/src/services/watch_status.js +101 -0
  61. package/dist/src/services/webhook.js +107 -3
  62. package/dist/src/store/migrations.js +63 -0
  63. package/dist/src/store/repos.d.ts +1 -1
  64. package/dist/src/store/rows.d.ts +6 -0
  65. package/dist/src/store/sessions.d.ts +3 -0
  66. package/dist/src/store/sessions.js +5 -0
  67. package/dist/src/store/watch.d.ts +108 -0
  68. package/dist/src/store/watch.js +186 -0
  69. package/dist/src/types.d.ts +2 -0
  70. package/dist/src/util/repo_name.d.ts +2 -0
  71. package/dist/src/util/repo_name.js +56 -0
  72. package/dist/src/util/runtime.js +7 -0
  73. package/dist/src/util/sanitize.d.ts +6 -0
  74. package/dist/src/util/sanitize.js +10 -0
  75. package/package.json +1 -1
@@ -13,8 +13,8 @@ const unifiedDiffArgs = [
13
13
  "--unified=3",
14
14
  ];
15
15
  /** Single-file unified patch when bulk `git diff` did not map a path. */
16
- export async function perFileUnifiedPatch(cwd, base, path, run) {
17
- const result = await run("git", [...diffEnv, ...unifiedDiffArgs, base, "--", path], cwd);
16
+ export async function perFileUnifiedPatch(cwd, base, path, run, to) {
17
+ const result = await run("git", [...diffEnv, ...unifiedDiffArgs, base, ...(to ? [to] : []), "--", path], cwd);
18
18
  if (result.code !== 0 || !result.stdout.trim())
19
19
  return "";
20
20
  const map = splitDiffPatches(result.stdout);
@@ -53,8 +53,13 @@ export async function resolveBaseRef(cwd, remote, toBranch, run) {
53
53
  }
54
54
  return { ref, label: `${remote}/${branch}` };
55
55
  }
56
- export async function buildLocalRevision(cwd, mergeBaseSha, baseLabel, run) {
57
- const base = mergeBaseSha;
56
+ /** The diff from `mergeBaseSha` to the working tree, untracked files
57
+ * included. With `to`, the diff between two commits instead, which is what a
58
+ * push review sends: nothing in the working tree is part of a push. */
59
+ export async function buildLocalRevision(cwd, mergeBaseSha, baseLabel, run, to) {
60
+ // `git diff <base>` compares with the working tree, `git diff <base> <to>`
61
+ // compares two commits. Every call below takes the same refs.
62
+ const refs = to ? [mergeBaseSha, to] : [mergeBaseSha];
58
63
  const nameStatus = await run("git", [
59
64
  ...diffEnv,
60
65
  "diff",
@@ -64,7 +69,7 @@ export async function buildLocalRevision(cwd, mergeBaseSha, baseLabel, run) {
64
69
  "-M",
65
70
  "--name-status",
66
71
  "-z",
67
- base,
72
+ ...refs,
68
73
  ], cwd);
69
74
  const numstat = await run("git", [
70
75
  ...diffEnv,
@@ -75,9 +80,9 @@ export async function buildLocalRevision(cwd, mergeBaseSha, baseLabel, run) {
75
80
  "-M",
76
81
  "--numstat",
77
82
  "-z",
78
- base,
83
+ ...refs,
79
84
  ], cwd);
80
- const unified = await run("git", [...diffEnv, ...unifiedDiffArgs, base], cwd);
85
+ const unified = await run("git", [...diffEnv, ...unifiedDiffArgs, ...refs], cwd);
81
86
  if (nameStatus.code !== 0) {
82
87
  throw new ReviewCliError("internal", "git diff failed.");
83
88
  }
@@ -106,14 +111,16 @@ export async function buildLocalRevision(cwd, mergeBaseSha, baseLabel, run) {
106
111
  if (needsPerFile.has(entry.path) &&
107
112
  file.status !== "removed" &&
108
113
  !file.binary) {
109
- file.patch = await perFileUnifiedPatch(cwd, base, entry.path, run);
114
+ file.patch = await perFileUnifiedPatch(cwd, mergeBaseSha, entry.path, run, to);
110
115
  }
111
116
  files.push(file);
112
117
  }
113
118
  const warnings = [];
114
119
  const tracked = new Set(files.map((f) => f.path));
115
- const untracked = await run("git", [...diffEnv, "ls-files", "--others", "--exclude-standard", "-z"], cwd);
116
- if (untracked.code === 0 && untracked.stdout) {
120
+ const untracked = to
121
+ ? undefined
122
+ : await run("git", [...diffEnv, "ls-files", "--others", "--exclude-standard", "-z"], cwd);
123
+ if (untracked && untracked.code === 0 && untracked.stdout) {
117
124
  for (const rel of untracked.stdout.split("\0").filter(Boolean)) {
118
125
  const path = normalizePath(rel);
119
126
  if (tracked.has(path))
@@ -1,15 +1,18 @@
1
1
  import { cloneDir, worktreeDir } from "../config.js";
2
2
  import { log } from "../util/log.js";
3
3
  import { withKeyedLock } from "../util/keyed_lock.js";
4
- import { commandOutput, isWindows, stat } from "../util/runtime.js";
4
+ import { commandOutput, stat } from "../util/runtime.js";
5
5
  export function withCloneLock(repo, fn) {
6
6
  return withKeyedLock(`clone:${repo}`, fn);
7
7
  }
8
8
  export async function runCommand(command, args, cwd) {
9
- // Windows resolves git and other shims through the shell, not as bare exes.
10
- const windows = isWindows();
11
- const output = await commandOutput(windows ? "cmd" : command, {
12
- args: windows ? ["/c", command, ...args] : args,
9
+ // Spawn the executable directly, never through `cmd /c`. git is a real .exe
10
+ // on Windows, so cmd is unnecessary, and routing a pull request's file paths
11
+ // through cmd let a path like `x&evil` run as a second command. `runtime.ts`
12
+ // also sets NoDefaultCurrentDirectoryInExePath=1 so the working directory is
13
+ // never searched for the executable.
14
+ const output = await commandOutput(command, {
15
+ args,
13
16
  cwd,
14
17
  stdout: "piped",
15
18
  stderr: "piped",
@@ -38,6 +41,8 @@ async function cloneInto(repo, dir, run) {
38
41
  const result = await run("git", [
39
42
  "-c",
40
43
  "core.longpaths=true",
44
+ "-c",
45
+ "core.symlinks=false",
41
46
  "clone",
42
47
  "--filter=blob:none",
43
48
  `https://github.com/${repo}`,
@@ -54,6 +59,10 @@ async function cloneInto(repo, dir, run) {
54
59
  `repository scope and falls back to the diff only` +
55
60
  (firstLine ? `: ${firstLine}` : ""));
56
61
  }
62
+ // A pull request may ship symlinks; without this a codegraph tool could read
63
+ // through one to a file outside the tree. Persist it in the clone so every
64
+ // worktree checkout writes symlinks as plain files instead of following them.
65
+ await run("git", ["config", "core.symlinks", "false"], dir);
57
66
  log("checkout", `cloned in ${((performance.now() - started) / 1000).toFixed(1)}s`);
58
67
  return dir;
59
68
  }
@@ -185,9 +185,11 @@ export function codegraphTools(binary, worktree, runner = createCodegraphRunner(
185
185
  return Promise.resolve("codegraph-node requires 'name' or 'file'.");
186
186
  }
187
187
  if (name) {
188
- const flag = rejectFlagLike(name, "name");
189
- if (flag)
190
- return Promise.resolve(flag);
188
+ // codegraph reads `name` as a file when it contains a slash, so hold
189
+ // it to the same in-repo check as `file`.
190
+ const nameErr = rejectEscapingPath(name);
191
+ if (nameErr)
192
+ return Promise.resolve(nameErr);
191
193
  }
192
194
  if (file) {
193
195
  const pathErr = rejectEscapingPath(file);
@@ -12,6 +12,8 @@ export type ReviewExtras = {
12
12
  carryPrompt?: string;
13
13
  unchangedPaths?: string[];
14
14
  prepareCodegraphTools?: () => Promise<ToolHandler[]>;
15
+ /** The request's job name, `review_local` when left out. */
16
+ job?: string;
15
17
  };
16
18
  export declare const MERMAID_GUIDANCE = "Mermaid selection and minimal syntax:\nflowchart = decisions, branches, pipelines, and fallback paths;\nswimlane-beta = work crossing owners, actors, services, teams, or layers;\nsequenceDiagram = ordered calls, webhooks, retries, responses, and timing;\nclassDiagram = class, interface, type, inheritance, or composition relationships;\nstateDiagram-v2 = lifecycle and state transitions;\nerDiagram = database entities, keys, and cardinality;\nrequirementDiagram = requirements linked to tests or implementation;\nusecase-beta = actors and system capabilities;\nC4Context = users, systems, boundaries, and integrations;\nzenuml = compact nested call sequences;\npacket = binary fields, bit ranges, and protocol layout;\narchitecture-beta = services, containers, storage, and deployment topology;\neventmodeling = commands, events, processors, read models, and timelines;\ntreeView-beta = directory, file, module, or dependency hierarchy.\nIf a diagram is useful, call read-mermaid-syntaxes before writing any Mermaid.\nRequest every type you need in a single call, because repeated tool rounds are\ncapped. Use the smallest type that matches the evidence.";
17
19
  /** Without tool support the model cannot read the Mermaid syntax docs, so
@@ -546,7 +546,7 @@ ${carryBlock}DIFF:
546
546
  ${ownDiff}${unchangedListing}`;
547
547
  const matrix = clampImproveMatrix(options.improveMatrix);
548
548
  const request = {
549
- job: "review_local",
549
+ job: extras?.job ?? "review_local",
550
550
  system: `${reviewSystemPrompt(diagrams)}\n\n${reviewGuidesBlock(guide, detailed, codebase)}${reviewSystemPromptBlock(options)}`,
551
551
  prompt,
552
552
  maxTokens: 24_000 * matrix,
@@ -5,6 +5,7 @@ import { formatHumanReview, humanFindingsFromJson, reviewExitCodeFromJsonFinding
5
5
  import { baseUrl, die, readApiError, remoteFetch, remoteFromEnv, } from "./http.js";
6
6
  import { readConfig, writeUserConfig } from "../config.js";
7
7
  import { getEnv } from "../util/runtime.js";
8
+ import { stripControlChars } from "../util/sanitize.js";
8
9
  import { prepareLocalCodegraph } from "../local/codegraph_prepare.js";
9
10
  import { canPrompt } from "../tools/codegraph.js";
10
11
  import { runRemoteToolCalls, toolHandlerMap, } from "./client_tools.js";
@@ -123,8 +124,9 @@ export async function runRemoteReview(cli) {
123
124
  const hostKey = baseUrl(host);
124
125
  const shown = config.remoteNoticeShownFor ?? [];
125
126
  if (!shown.includes(hostKey) && !cli.json) {
126
- console.error("Remote review sends your unpublished diff to the server you configured. " +
127
- "Use a host you trust.");
127
+ console.error("Remote review sends your unpublished diff to the server you configured, " +
128
+ "and the server may ask it to read other files in this repository while " +
129
+ "reviewing. Use a host you trust.");
128
130
  await writeUserConfig({
129
131
  remoteNoticeShownFor: [...shown, hostKey],
130
132
  });
@@ -185,6 +187,10 @@ export async function runRemoteReview(cli) {
185
187
  const { jobId } = (await submit.json());
186
188
  let afterLogSeq = 0;
187
189
  let toolResults = [];
190
+ let toolCallsRun = 0;
191
+ // A trustworthy server drives at most a few tool rounds; cap the total so a
192
+ // malicious one cannot make the client read its tree without limit.
193
+ const MAX_REMOTE_TOOL_CALLS = 200;
188
194
  const intervalMs = hs.sync.intervalSeconds * 1000;
189
195
  while (true) {
190
196
  const sync = await remoteFetch(host, token, `/api/remote/reviews/${jobId}/sync`, {
@@ -205,10 +211,14 @@ export async function runRemoteReview(cli) {
205
211
  if (!cli.json) {
206
212
  console.error(cli.output === "github"
207
213
  ? neutralizeCommands(line.message)
208
- : line.message);
214
+ : stripControlChars(line.message));
209
215
  }
210
216
  }
211
217
  if (payload.toolCalls?.length) {
218
+ toolCallsRun += payload.toolCalls.length;
219
+ if (toolCallsRun > MAX_REMOTE_TOOL_CALLS) {
220
+ die("remote_tool_calls_exceeded", `the server asked for more than ${MAX_REMOTE_TOOL_CALLS} tool calls`);
221
+ }
212
222
  toolResults = await runRemoteToolCalls(payload.toolCalls, localTools);
213
223
  continue;
214
224
  }
@@ -265,7 +275,7 @@ export async function runRemoteReview(cli) {
265
275
  return;
266
276
  }
267
277
  if (payload.status === "failed" || payload.status === "canceled") {
268
- die(payload.abort?.reason ?? "remote_failed", payload.abort?.message ?? "Remote review did not complete.");
278
+ die(stripControlChars(payload.abort?.reason ?? "remote_failed"), stripControlChars(payload.abort?.message ?? "Remote review did not complete."));
269
279
  }
270
280
  await new Promise((resolve) => setTimeout(resolve, intervalMs));
271
281
  }
@@ -0,0 +1,7 @@
1
+ import type { ReviewCliArgs } from "../cli/review_args.ts";
2
+ export declare const DEFAULT_PUSH_TIMEOUT_MINUTES = 10;
3
+ type Cli = ReviewCliArgs & {
4
+ mode: "remote";
5
+ };
6
+ export declare function runRemotePushReview(cli: Cli): Promise<void>;
7
+ export {};
@@ -0,0 +1,287 @@
1
+ /** `co-maintainer review --remote --range=<before>..<after>`: commit watch
2
+ * from CI.
3
+ *
4
+ * The step sends the push's diff and waits for the server's review. What it
5
+ * reports and how it exits:
6
+ * - findings are warnings, and the step stays green: the push is already in,
7
+ * so there is nothing to block.
8
+ * - a review still running after `--timeout-minutes` (default 10) leaves a
9
+ * notice and stays green. The server finishes the review on its own.
10
+ * - a push merged into a newer push's review leaves a notice and stays green.
11
+ * - a repository that is not initialized is red, unless the GitHub App gave
12
+ * the commit a skipped check run: then it is a notice.
13
+ * - a server that cannot be reached or rejects the token is red. */
14
+ import { VERSION } from "../version.js";
15
+ import { exitWith } from "../cli/error.js";
16
+ import { formatHumanReview, humanFindingsFromJson, } from "../cli/review_result.js";
17
+ import { baseUrl, die, readApiError, remoteFetch, remoteFromEnv, } from "./http.js";
18
+ import { readConfig } from "../config.js";
19
+ import { stripControlChars } from "../util/sanitize.js";
20
+ import { runCommand } from "../pr/checkout.js";
21
+ import { assertGitQuiet, currentBranch, detectRemoteRepo, gitRoot, } from "../local/git_ops.js";
22
+ import { buildLocalRevision } from "../local/git_revision.js";
23
+ import { withCliLogsToStderr } from "../util/log.js";
24
+ import { emitGithubOutput, escapeData, neutralizeCommands, } from "../cli/review_github.js";
25
+ import { setCliInteractive } from "../cli/args.js";
26
+ import { MIN_SERVER_SCHEMA, REMOTE_CLI_UPGRADE_COMMAND, REMOTE_SCHEMA_VERSION, } from "./schema.js";
27
+ export const DEFAULT_PUSH_TIMEOUT_MINUTES = 10;
28
+ const ZERO = /^0+$/;
29
+ /** A notice the step shows and that never fails it. */
30
+ function notice(cli, message) {
31
+ if (cli.json) {
32
+ console.log(JSON.stringify({ schemaVersion: 1, ok: true, mode: "push", message }));
33
+ }
34
+ else if (cli.output === "github") {
35
+ console.log(`::notice title=co-maintainer::${escapeData(message)}`);
36
+ }
37
+ else {
38
+ console.log(message);
39
+ }
40
+ }
41
+ async function git(root, args) {
42
+ return await runCommand("git", args, root);
43
+ }
44
+ async function resolveCommit(root, rev) {
45
+ const result = await git(root, [
46
+ "rev-parse",
47
+ "--verify",
48
+ "--quiet",
49
+ `${rev}^{commit}`,
50
+ ]);
51
+ return result.code === 0 ? result.stdout.trim() : undefined;
52
+ }
53
+ /** `rev` as a full sha, fetching it from the remote when the checkout does
54
+ * not have it (a shallow CI checkout usually holds only `after`). */
55
+ async function ensureCommit(root, remote, rev) {
56
+ const local = await resolveCommit(root, rev);
57
+ if (local)
58
+ return local;
59
+ await git(root, ["fetch", "--quiet", "--no-tags", remote, rev]);
60
+ return await resolveCommit(root, rev);
61
+ }
62
+ /** Where the diff starts. `before` itself after a normal push. After a
63
+ * force-push `before` is no longer an ancestor, so the commits since the
64
+ * merge base. When `before` cannot be fetched at all, the last commit, with
65
+ * a warning. */
66
+ async function diffBase(root, remote, before, after) {
67
+ const have = await ensureCommit(root, remote, before);
68
+ if (have) {
69
+ let base = await git(root, ["merge-base", have, after]);
70
+ if (base.code !== 0) {
71
+ // A shallow checkout can hold both commits and still not their history.
72
+ await git(root, ["fetch", "--quiet", "--no-tags", "--unshallow", remote]);
73
+ base = await git(root, ["merge-base", have, after]);
74
+ }
75
+ if (base.code === 0 && base.stdout.trim())
76
+ return base.stdout.trim();
77
+ }
78
+ console.error(`Warning: could not fetch ${before.slice(0, 7)}, so only the last commit of this push is reviewed.`);
79
+ // `after^` is no refspec git can fetch, so a depth-one checkout is deepened
80
+ // by one commit to bring the parent in.
81
+ let parent = await resolveCommit(root, `${after}^`);
82
+ if (!parent) {
83
+ await git(root, ["fetch", "--quiet", "--no-tags", "--deepen=1", remote]);
84
+ parent = await resolveCommit(root, `${after}^`);
85
+ }
86
+ if (!parent) {
87
+ die("push_base_missing", "Could not find the commit this push starts from.");
88
+ }
89
+ return parent;
90
+ }
91
+ async function readError(response) {
92
+ try {
93
+ const body = (await response.clone().json());
94
+ return body.error ?? {};
95
+ }
96
+ catch {
97
+ return { message: await readApiError(response) };
98
+ }
99
+ }
100
+ export async function runRemotePushReview(cli) {
101
+ const range = cli.range;
102
+ const config = readConfig();
103
+ const fromEnv = remoteFromEnv();
104
+ const host = cli.remoteHost ?? fromEnv.host ?? config.remoteHost;
105
+ const token = cli.remoteToken ?? fromEnv.token ?? config.remoteToken;
106
+ if (!host || !token) {
107
+ die("remote_not_configured", "Remote review is not configured.", "set CM_REMOTE_HOST and CM_REMOTE_TOKEN, or pass --remote-host=... --remote-token=...");
108
+ }
109
+ setCliInteractive(!cli.json);
110
+ await withCliLogsToStderr(async () => {
111
+ // A push that creates the branch has no "before": there is nothing it
112
+ // changed to compare with.
113
+ if (ZERO.test(range.before)) {
114
+ notice(cli, "No changes to review.");
115
+ exitWith(0);
116
+ return;
117
+ }
118
+ const root = await gitRoot(process.cwd());
119
+ await assertGitQuiet(root);
120
+ const repo = await detectRemoteRepo(root, cli.repoOverride);
121
+ const branch = await currentBranch(root, cli.branch);
122
+ const remotes = (await git(root, ["remote"])).stdout
123
+ .split("\n")
124
+ .map((line) => line.trim())
125
+ .filter(Boolean);
126
+ const remoteName = ["upstream", "origin"].find((name) => remotes.includes(name)) ??
127
+ remotes[0];
128
+ const after = await ensureCommit(root, remoteName, range.after);
129
+ if (!after)
130
+ die("push_after_missing", `Could not find ${range.after} in this checkout.`);
131
+ let before = (await resolveCommit(root, range.before)) ?? range.before;
132
+ const handshake = await remoteFetch(host, token, "/api/remote/handshake", {
133
+ method: "POST",
134
+ body: JSON.stringify({
135
+ schemaVersion: REMOTE_SCHEMA_VERSION,
136
+ clientVersion: VERSION,
137
+ repo,
138
+ purpose: "push",
139
+ }),
140
+ });
141
+ if (!handshake.ok)
142
+ die("remote_handshake_failed", await readApiError(handshake));
143
+ const hs = (await handshake.json());
144
+ if (REMOTE_SCHEMA_VERSION < hs.minClientSchema) {
145
+ die("upgrade_required", "This co-maintainer CLI is too old for the server.", REMOTE_CLI_UPGRADE_COMMAND, 4);
146
+ }
147
+ if (hs.schemaVersion < MIN_SERVER_SCHEMA ||
148
+ !hs.features?.includes("push")) {
149
+ die("server_too_old", `This server (version ${hs.serverVersion}) cannot review pushes.`, "Upgrade the server to 0.6.10 or later.", 4);
150
+ }
151
+ let submitted;
152
+ // At most one retry: the server asks for a wider range when this push
153
+ // was merged into a waiting review that only this step can diff.
154
+ for (let attempt = 0; attempt < 2 && !submitted; attempt++) {
155
+ const base = await diffBase(root, remoteName, before, after);
156
+ const built = await buildLocalRevision(root, base, branch, runCommand, after);
157
+ if (built.revision.files.length === 0 && attempt === 0) {
158
+ notice(cli, "No changes to review.");
159
+ exitWith(0);
160
+ return;
161
+ }
162
+ const body = JSON.stringify({
163
+ schemaVersion: REMOTE_SCHEMA_VERSION,
164
+ requestId: crypto.randomUUID(),
165
+ repo: hs.repo.fullName,
166
+ branch,
167
+ revision: {
168
+ title: "",
169
+ description: "",
170
+ baseLabel: branch,
171
+ files: built.revision.files,
172
+ },
173
+ push: { before, after, ref: `refs/heads/${branch}` },
174
+ });
175
+ if (body.length > hs.limits.maxBodyBytes) {
176
+ die("payload_too_large", "This push is too large for the remote server limit.");
177
+ }
178
+ const submit = await remoteFetch(host, token, "/api/remote/reviews", {
179
+ method: "POST",
180
+ body,
181
+ });
182
+ if (submit.status === 202) {
183
+ submitted = (await submit.json());
184
+ break;
185
+ }
186
+ if (submit.status === 200) {
187
+ notice(cli, "No changes to review.");
188
+ exitWith(0);
189
+ return;
190
+ }
191
+ const error = await readError(submit);
192
+ if (error.code === "range_extend" &&
193
+ error.detail?.before &&
194
+ attempt === 0) {
195
+ before = error.detail.before;
196
+ continue;
197
+ }
198
+ if (error.code === "not_initialized_skipped") {
199
+ notice(cli, `${error.message ?? "This repository is not initialized."} The commit got a skipped check run.`);
200
+ exitWith(0);
201
+ return;
202
+ }
203
+ if (error.code === "not_default_branch") {
204
+ notice(cli, error.message ?? "Commit watch reviews the default branch only.");
205
+ exitWith(0);
206
+ return;
207
+ }
208
+ die(error.code ?? "remote_submit_failed", error.message ?? "The server refused the push.");
209
+ }
210
+ if (!submitted)
211
+ die("remote_submit_failed", "The server refused the push.");
212
+ if (submitted.attached && !cli.json) {
213
+ console.error("The GitHub App is already reviewing this push, waiting for that review.");
214
+ }
215
+ const deadline = Date.now() +
216
+ (cli.timeoutMinutes ?? DEFAULT_PUSH_TIMEOUT_MINUTES) * 60_000;
217
+ const intervalMs = hs.sync.intervalSeconds * 1000;
218
+ let afterLogSeq = 0;
219
+ for (;;) {
220
+ const sync = await remoteFetch(host, token, `/api/remote/reviews/${submitted.jobId}/sync`, {
221
+ method: "POST",
222
+ body: JSON.stringify({
223
+ schemaVersion: REMOTE_SCHEMA_VERSION,
224
+ afterLogSeq,
225
+ toolResults: [],
226
+ }),
227
+ });
228
+ if (!sync.ok)
229
+ die("remote_sync_failed", await readApiError(sync));
230
+ const payload = (await sync.json());
231
+ for (const line of payload.logs ?? []) {
232
+ afterLogSeq = Math.max(afterLogSeq, line.seq);
233
+ if (!cli.json) {
234
+ console.error(cli.output === "github"
235
+ ? neutralizeCommands(line.message)
236
+ : stripControlChars(line.message));
237
+ }
238
+ }
239
+ if (payload.status === "done" && payload.result) {
240
+ const findings = (payload.result.findings ?? []);
241
+ const title = `${repo} · ${branch} · ${before.slice(0, 7)}..${after.slice(0, 7)}`;
242
+ // A push review never blocks, so every finding is a warning.
243
+ const human = humanFindingsFromJson(findings).map((row) => ({
244
+ ...row,
245
+ blocking: false,
246
+ }));
247
+ if (cli.json) {
248
+ console.log(JSON.stringify({
249
+ schemaVersion: 1,
250
+ ok: true,
251
+ mode: "push",
252
+ ...payload.result,
253
+ }));
254
+ }
255
+ else if (cli.output === "github") {
256
+ emitGithubOutput({ title, findings: human });
257
+ }
258
+ else {
259
+ console.log("\n" +
260
+ formatHumanReview({
261
+ title: `co-maintainer commit watch · ${title}`,
262
+ guideBuiltAt: null,
263
+ codegraphState: null,
264
+ findings: human,
265
+ }) +
266
+ "\n");
267
+ }
268
+ exitWith(0);
269
+ return;
270
+ }
271
+ if (payload.status === "canceled" && payload.abort?.reason === "merged") {
272
+ notice(cli, `${stripControlChars(payload.abort.message)} The result is on the dashboard.`);
273
+ exitWith(0);
274
+ return;
275
+ }
276
+ if (payload.status === "failed" || payload.status === "canceled") {
277
+ die(stripControlChars(payload.abort?.reason ?? "remote_failed"), stripControlChars(payload.abort?.message ?? "The push review did not complete."));
278
+ }
279
+ if (Date.now() >= deadline) {
280
+ notice(cli, `The review is still running on ${baseUrl(host)}. The result will be on the dashboard.`);
281
+ exitWith(0);
282
+ return;
283
+ }
284
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
285
+ }
286
+ });
287
+ }
@@ -1,4 +1,11 @@
1
1
  /** Bounded request body read (bytes, streaming). */
2
+ export type BoundedBytesResult = {
3
+ ok: true;
4
+ bytes: Uint8Array;
5
+ } | {
6
+ ok: false;
7
+ reason: "too_large";
8
+ };
2
9
  export type BoundedBodyResult = {
3
10
  ok: true;
4
11
  text: string;
@@ -6,6 +13,10 @@ export type BoundedBodyResult = {
6
13
  ok: false;
7
14
  reason: "too_large" | "empty";
8
15
  };
16
+ /** Reads the raw body, streaming, and refuses once more than `maxBytes` have
17
+ * arrived — this holds with no Content-Length (chunked) too. The caller gets
18
+ * the exact bytes, which the webhook HMAC needs. */
19
+ export declare function readBoundedBytes(request: Request, maxBytes: number): Promise<BoundedBytesResult>;
9
20
  export declare function readBoundedUtf8(request: Request, maxBytes: number): Promise<BoundedBodyResult>;
10
21
  export declare function readBoundedJson(request: Request, maxBytes: number): Promise<{
11
22
  ok: true;
@@ -1,5 +1,8 @@
1
1
  /** Bounded request body read (bytes, streaming). */
2
- export async function readBoundedUtf8(request, maxBytes) {
2
+ /** Reads the raw body, streaming, and refuses once more than `maxBytes` have
3
+ * arrived — this holds with no Content-Length (chunked) too. The caller gets
4
+ * the exact bytes, which the webhook HMAC needs. */
5
+ export async function readBoundedBytes(request, maxBytes) {
3
6
  const lengthHeader = request.headers.get("content-length");
4
7
  if (lengthHeader !== null) {
5
8
  const declared = Number(lengthHeader);
@@ -9,7 +12,7 @@ export async function readBoundedUtf8(request, maxBytes) {
9
12
  }
10
13
  const stream = request.body;
11
14
  if (!stream)
12
- return { ok: true, text: "" };
15
+ return { ok: true, bytes: new Uint8Array(0) };
13
16
  const reader = stream.getReader();
14
17
  const chunks = [];
15
18
  let total = 0;
@@ -31,15 +34,21 @@ export async function readBoundedUtf8(request, maxBytes) {
31
34
  finally {
32
35
  reader.releaseLock();
33
36
  }
34
- if (total === 0)
35
- return { ok: true, text: "" };
36
37
  const merged = new Uint8Array(total);
37
38
  let offset = 0;
38
39
  for (const chunk of chunks) {
39
40
  merged.set(chunk, offset);
40
41
  offset += chunk.length;
41
42
  }
42
- return { ok: true, text: new TextDecoder().decode(merged) };
43
+ return { ok: true, bytes: merged };
44
+ }
45
+ export async function readBoundedUtf8(request, maxBytes) {
46
+ const body = await readBoundedBytes(request, maxBytes);
47
+ if (!body.ok)
48
+ return { ok: false, reason: "too_large" };
49
+ if (body.bytes.length === 0)
50
+ return { ok: true, text: "" };
51
+ return { ok: true, text: new TextDecoder().decode(body.bytes) };
43
52
  }
44
53
  export async function readBoundedJson(request, maxBytes) {
45
54
  const body = await readBoundedUtf8(request, maxBytes);
@@ -1 +1,2 @@
1
+ export declare function defaultBranchForRepo(fullName: string): Promise<string | null>;
1
2
  export declare function handleRemoteRoute(request: Request, url: URL, remoteAddr: string): Promise<Response>;