co-maintainer 0.6.9 → 0.6.11

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 (66) 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 +4 -0
  11. package/dist/src/cli/commands/set.js +4 -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/github/app.d.ts +4 -0
  15. package/dist/src/github/app.js +10 -1
  16. package/dist/src/github/permissions.js +40 -0
  17. package/dist/src/github/write_access.d.ts +7 -0
  18. package/dist/src/github/write_access.js +12 -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/reviewer.d.ts +2 -0
  23. package/dist/src/pr/reviewer.js +1 -1
  24. package/dist/src/remote/push_client.d.ts +7 -0
  25. package/dist/src/remote/push_client.js +287 -0
  26. package/dist/src/remote/server/routes.d.ts +1 -0
  27. package/dist/src/remote/server/routes.js +61 -4
  28. package/dist/src/remote/server/sync.js +11 -3
  29. package/dist/src/remote/validate.js +17 -0
  30. package/dist/src/review/carry_over.d.ts +2 -0
  31. package/dist/src/review/carry_over.js +33 -26
  32. package/dist/src/server/api/repos.js +13 -2
  33. package/dist/src/server/pages/layout.js +1 -0
  34. package/dist/src/server/pages/repo.d.ts +3 -1
  35. package/dist/src/server/pages/repo.js +4 -1
  36. package/dist/src/server/pages/repo_pushes.d.ts +7 -0
  37. package/dist/src/server/pages/repo_pushes.js +144 -0
  38. package/dist/src/server/pages/repo_settings.js +45 -1
  39. package/dist/src/server/pages/router.js +22 -3
  40. package/dist/src/server/webhook/index.js +8 -1
  41. package/dist/src/services/dashboard.d.ts +46 -0
  42. package/dist/src/services/dashboard.js +24 -0
  43. package/dist/src/services/jobs.js +10 -0
  44. package/dist/src/services/push_review.d.ts +51 -0
  45. package/dist/src/services/push_review.js +878 -0
  46. package/dist/src/services/review.d.ts +20 -3
  47. package/dist/src/services/review.js +112 -39
  48. package/dist/src/services/setup.js +21 -0
  49. package/dist/src/services/watch_comments.d.ts +10 -0
  50. package/dist/src/services/watch_comments.js +166 -0
  51. package/dist/src/services/watch_issues.d.ts +70 -0
  52. package/dist/src/services/watch_issues.js +266 -0
  53. package/dist/src/services/watch_notes.d.ts +8 -0
  54. package/dist/src/services/watch_notes.js +80 -0
  55. package/dist/src/services/watch_status.d.ts +25 -0
  56. package/dist/src/services/watch_status.js +101 -0
  57. package/dist/src/services/webhook.js +108 -8
  58. package/dist/src/store/migrations.js +63 -0
  59. package/dist/src/store/repos.d.ts +1 -1
  60. package/dist/src/store/rows.d.ts +6 -0
  61. package/dist/src/store/watch.d.ts +108 -0
  62. package/dist/src/store/watch.js +186 -0
  63. package/dist/src/types.d.ts +2 -0
  64. package/dist/src/util/repo_name.d.ts +2 -0
  65. package/dist/src/util/repo_name.js +56 -0
  66. package/package.json +1 -1
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "co-maintainer",
3
- "version": "0.6.9",
3
+ "version": "0.6.11",
4
4
  "description": "An imitator of yours, A PR review tool like co-maintainer.",
5
5
  "keywords": [
6
6
  "ai",
@@ -3,5 +3,14 @@ export declare const FAKE_REVIEW_MARKDOWN = "## Findings\n\n### [P2 \u00B7 non-b
3
3
  export declare class FakeAiProvider implements AiProvider {
4
4
  private readonly text;
5
5
  constructor(text?: string);
6
- complete(_request: AiRequest): Promise<AiResponse>;
6
+ /** `CM_FAKE_AI_DIR/<job>.txt`, when it exists, answers that one job, so a
7
+ * smoke test can give the comment classifier and the review different
8
+ * answers. It is read on every call, so a test can change it between
9
+ * pushes. */
10
+ private jobText;
11
+ /** With `CM_FAKE_AI_DIR`, each request is appended to `requests.jsonl` so a
12
+ * smoke test can read what was asked, and `delay_ms` slows every answer so
13
+ * it can catch a review while it runs. */
14
+ private record;
15
+ complete(request: AiRequest): Promise<AiResponse>;
7
16
  }
@@ -27,14 +27,49 @@ export class FakeAiProvider {
27
27
  constructor(text = fakeReviewText()) {
28
28
  this.text = text;
29
29
  }
30
- complete(_request) {
31
- return Promise.resolve({
32
- text: this.text,
30
+ /** `CM_FAKE_AI_DIR/<job>.txt`, when it exists, answers that one job, so a
31
+ * smoke test can give the comment classifier and the review different
32
+ * answers. It is read on every call, so a test can change it between
33
+ * pushes. */
34
+ jobText(job) {
35
+ const dir = getEnv("CM_FAKE_AI_DIR");
36
+ if (!dir || !/^[a-z_]+$/.test(job))
37
+ return undefined;
38
+ try {
39
+ return readTextFileSync(`${dir}/${job}.txt`);
40
+ }
41
+ catch {
42
+ return undefined;
43
+ }
44
+ }
45
+ /** With `CM_FAKE_AI_DIR`, each request is appended to `requests.jsonl` so a
46
+ * smoke test can read what was asked, and `delay_ms` slows every answer so
47
+ * it can catch a review while it runs. */
48
+ async record(request) {
49
+ const dir = getEnv("CM_FAKE_AI_DIR");
50
+ if (!dir)
51
+ return;
52
+ const { appendFileSync } = await import("node:fs");
53
+ appendFileSync(`${dir}/requests.jsonl`, `${JSON.stringify({ job: request.job, system: request.system ?? "", prompt: request.prompt })}\n`);
54
+ let delay = 0;
55
+ try {
56
+ delay = Number(readTextFileSync(`${dir}/delay_ms`).trim()) || 0;
57
+ }
58
+ catch {
59
+ // no delay
60
+ }
61
+ if (delay > 0)
62
+ await new Promise((resolve) => setTimeout(resolve, delay));
63
+ }
64
+ async complete(request) {
65
+ await this.record(request);
66
+ return {
67
+ text: this.jobText(request.job) ?? this.text,
33
68
  tokensIn: 10,
34
69
  tokensOut: 20,
35
70
  cost: 0,
36
71
  model: "fake",
37
72
  provider: "openrouter",
38
- });
73
+ };
39
74
  }
40
75
  }
@@ -6,6 +6,7 @@ import { die } from "./error.js";
6
6
  import { AI_PROVIDERS, providerKeyEnv, rejectRetiredProvider, } from "../ai/provider.js";
7
7
  import { availableModelSlugs } from "../ai/oauth/sign-in-with-chatgpt.js";
8
8
  import { detectRemoteRepo } from "../local/git_ops.js";
9
+ import { canonicalRepoName } from "../util/repo_name.js";
9
10
  import { reviewBlockingFrom } from "../review/blocking.js";
10
11
  import { renderCommandHelp, renderGlobalHelp, unknownCommandMessage, unknownOptionMessage, } from "./commands/registry.js";
11
12
  function numberOption(value, name) {
@@ -66,6 +67,7 @@ export async function parseArgs(args) {
66
67
  if (!repoName || !/^[^/]+\/[^/]+$/.test(repoName)) {
67
68
  die("Repository must look like owner/repo");
68
69
  }
70
+ repoName = canonicalRepoName(repoName);
69
71
  const { config, envPath } = prepareConfig(args);
70
72
  const env = (name) => getEnv(name);
71
73
  const configDefault = config.defaults ?? {};
@@ -24,6 +24,12 @@ export type ProbeJsonInput = {
24
24
  /** The prose cost line, kept so a missing dollar range still says why. */
25
25
  costNote: string;
26
26
  durationMs: number;
27
+ /** Commit watch through the GitHub App. Left out when this machine has no
28
+ * App configured, since nothing can be said then. */
29
+ commitWatch?: {
30
+ app: "on" | "off";
31
+ branch: string | null;
32
+ };
27
33
  };
28
34
  export declare function buildProbeJson(input: ProbeJsonInput): string;
29
35
  export type SetupJsonInput = {
@@ -17,6 +17,7 @@ export function buildProbeJson(input) {
17
17
  cost: input.costNote,
18
18
  basis: estimate.basis,
19
19
  },
20
+ ...(input.commitWatch ? { commitWatch: input.commitWatch } : {}),
20
21
  durationMs: input.durationMs,
21
22
  });
22
23
  }
@@ -5,6 +5,7 @@ import { estimateCostLine, estimateInit, readJobHistory, } from "../../ai/estima
5
5
  import { loadPrices } from "../../ai/pricing.js";
6
6
  import { cacheSet } from "../../store/cache_db.js";
7
7
  import { buildProbeJson } from "../command_json.js";
8
+ import { appPushStateWithoutDb } from "../../services/watch_status.js";
8
9
  export async function runProbe(options) {
9
10
  // With `--json` stdout carries the one document, so progress moves to stderr.
10
11
  if (options.json)
@@ -48,6 +49,7 @@ async function probe(options) {
48
49
  history,
49
50
  });
50
51
  const costLine = estimateCostLine(estimate, options.ai, needsPrices && prices.source === "unavailable");
52
+ const commitWatch = await commitWatchState(client, options.repo);
51
53
  if (options.json) {
52
54
  stopHeartbeat();
53
55
  console.log(buildProbeJson({
@@ -66,6 +68,7 @@ async function probe(options) {
66
68
  estimate,
67
69
  costNote: costLine,
68
70
  durationMs: Math.round(performance.now() - operationStarted),
71
+ commitWatch,
69
72
  }));
70
73
  return;
71
74
  }
@@ -84,6 +87,11 @@ async function probe(options) {
84
87
  console.log(` basis: ${estimate.basis === "history"
85
88
  ? "this repository's recorded jobs"
86
89
  : "the cm-dx-lab calibration"}; an estimate, not a bill`);
90
+ if (commitWatch) {
91
+ console.log(`\ncommit watch ${commitWatch.app === "on"
92
+ ? "✓ App (push event on)"
93
+ : "○ App (push event off)"} ${commitWatch.branch ?? ""}`.trimEnd());
94
+ }
87
95
  console.log("\nnext");
88
96
  console.log(` ${command}`);
89
97
  console.log(` or run it now: co-maintainer probe ${options.repo} --run`);
@@ -100,6 +108,23 @@ async function probe(options) {
100
108
  await runInitOrRemake(options);
101
109
  }
102
110
  }
111
+ /** Commit watch through the App, when this machine has the App configured.
112
+ * Without it there is nothing to say and the line is left out. */
113
+ async function commitWatchState(client, repo) {
114
+ const app = await appPushStateWithoutDb(repo);
115
+ if (!app)
116
+ return undefined;
117
+ let branch = null;
118
+ try {
119
+ const info = await client.request(`repos/${repo}`);
120
+ branch =
121
+ typeof info.default_branch === "string" ? info.default_branch : null;
122
+ }
123
+ catch {
124
+ // The line still says whether the App watches.
125
+ }
126
+ return { app, branch };
127
+ }
103
128
  /** `120-190` for a token range, rounded to whole tokens. */
104
129
  function range([low, high]) {
105
130
  const round = (value) => Math.round(value).toLocaleString("en-US");
@@ -419,6 +419,16 @@ export const COMMANDS = [
419
419
  value: "PATH",
420
420
  description: "Replace the repository's review instructions with this file for this run only. The built-in instructions are kept.",
421
421
  },
422
+ {
423
+ name: "range",
424
+ value: "BEFORE..AFTER",
425
+ description: "With --remote: review a push (commit watch). The server keeps the review going if this run stops waiting.",
426
+ },
427
+ {
428
+ name: "timeout-minutes",
429
+ value: "N",
430
+ description: "With --range: stop waiting after N minutes and leave the result to the dashboard. Default 10.",
431
+ },
422
432
  ],
423
433
  },
424
434
  AI_FLAGS,
@@ -433,6 +443,7 @@ export const COMMANDS = [
433
443
  "co-maintainer review --remote --remote-host=https://review.example.com --remote-token=cmr_...",
434
444
  "co-maintainer review --remote --remote-byok --json",
435
445
  "co-maintainer review --remote --output=github",
446
+ "co-maintainer review --remote --range=abc1234..def5678 --output=github",
436
447
  "co-maintainer review owner/repo 42 --system-prompt-file=extra.md",
437
448
  "co-maintainer review --system-prompt-override-file=strict.md",
438
449
  ],
@@ -8,6 +8,7 @@ import { GhClient } from "../../github/gh.js";
8
8
  import { log, startHeartbeat, timed, withCliLogsToStderr, } from "../../util/log.js";
9
9
  import { runLocalReview } from "../../local/review_local.js";
10
10
  import { runRemoteReview } from "../../remote/client.js";
11
+ import { runRemotePushReview } from "../../remote/push_client.js";
11
12
  import { reviewExitCode } from "../review_output.js";
12
13
  import { buildPrReviewJson, resolvedFromFirstReview, reviewExitCodeFromResolved, } from "../review_result.js";
13
14
  import { parseFindings } from "../../pr/findings.js";
@@ -22,7 +23,10 @@ export async function runReviewFromCli(args) {
22
23
  return;
23
24
  }
24
25
  if (parsed.mode === "remote") {
25
- await runRemoteReview(parsed);
26
+ if (parsed.range)
27
+ await runRemotePushReview(parsed);
28
+ else
29
+ await runRemoteReview(parsed);
26
30
  return;
27
31
  }
28
32
  await runReviewPr(parsed.options, parsed);
@@ -10,6 +10,8 @@ import { registerReviewJobHandler } from "../../services/review.js";
10
10
  import { recoverReplyRequests, registerReplyJobHandler, } from "../../services/replies.js";
11
11
  import { startRemakeScheduler, stopRemakeScheduler, } from "../../services/remake_cron.js";
12
12
  import { registerRemoteReviewHandler } from "../../services/remote_review.js";
13
+ import { registerPushReviewHandlers } from "../../services/push_review.js";
14
+ import { registerWatchCommentHandler } from "../../services/watch_comments.js";
13
15
  import { startRemoteWatchdog } from "../../remote/server/sessions.js";
14
16
  import { passwordProblem } from "../../util/password.js";
15
17
  import { deleteAllSessions } from "../../store/sessions.js";
@@ -173,6 +175,8 @@ export async function runServe(args) {
173
175
  registerReviewJobHandler();
174
176
  registerRemoteReviewHandler();
175
177
  registerReplyJobHandler();
178
+ registerPushReviewHandlers();
179
+ registerWatchCommentHandler();
176
180
  const recovered = await recoverOrphans();
177
181
  if (recovered > 0) {
178
182
  console.log(`[serve] recovered ${recovered} orphaned job(s) from a previous run`);
@@ -1,5 +1,6 @@
1
1
  import { readConfig, configPath, savedKeyProvider, writeRepoConfig, writeUserConfig, } from "../../config.js";
2
2
  import { checkReviewSystemPrompt, reviewSystemPromptLimit, } from "../../review/system_prompt.js";
3
+ import { canonicalRepoName } from "../../util/repo_name.js";
3
4
  import { hashPassword, passwordProblem } from "../../util/password.js";
4
5
  import { deleteAllSessions } from "../../store/sessions.js";
5
6
  import { appDbPath, closeAppDb, openAppDb } from "../../store/app_db.js";
@@ -402,9 +403,10 @@ const REPO_SCOPED_UNSET = new Set([
402
403
  /** `set --repo=owner/repo [--review-system-prompt=... | --review-system-prompt-max-chars=N | --unset=name]`
403
404
  * writes the repository-scoped settings to `repos[owner/repo]` in config.json
404
405
  * instead of the global config. */
405
- async function runSetRepo(repo, args) {
406
- if (!/^[^/]+\/[^/]+$/.test(repo))
406
+ async function runSetRepo(typed, args) {
407
+ if (!/^[^/]+\/[^/]+$/.test(typed))
407
408
  die("--repo must look like owner/repo");
409
+ const repo = canonicalRepoName(typed);
408
410
  for (const arg of args) {
409
411
  if (!arg.startsWith("--"))
410
412
  continue;
@@ -26,6 +26,15 @@ type ReviewFlags = {
26
26
  /** `--system-prompt-override-file`: a file whose contents replace the
27
27
  * repository's custom review section for this run only. */
28
28
  systemPromptOverrideFile?: string;
29
+ /** `--range=<before>..<after>`: review a push instead of the working tree
30
+ * (commit watch). Only with `--remote`. */
31
+ range?: {
32
+ before: string;
33
+ after: string;
34
+ };
35
+ /** `--timeout-minutes`: how long a `--range` review waits for the server
36
+ * before it leaves the result to the dashboard. */
37
+ timeoutMinutes?: number;
29
38
  };
30
39
  export type ReviewCliArgs = ({
31
40
  mode: "pr";
@@ -3,6 +3,28 @@ import { die } from "./error.js";
3
3
  import { readConfig } from "../config.js";
4
4
  import { readTextFile } from "../util/runtime.js";
5
5
  import { checkReviewSystemPrompt, reviewSystemPromptLimit, } from "../review/system_prompt.js";
6
+ /** `before..after`. Each side is any revision git can resolve. */
7
+ function parseRange(value) {
8
+ if (value === undefined)
9
+ return undefined;
10
+ // A side may hold single dots (v0.6.9), never two in a row, so `..` splits
11
+ // once and `a...b` is refused.
12
+ const sides = value.split("..");
13
+ const valid = (side) => Boolean(side) && /^[^\s-][^\s]*$/.test(side) && !/^\.|\.$/.test(side);
14
+ if (sides.length !== 2 || !valid(sides[0]) || !valid(sides[1])) {
15
+ die("--range must look like <before>..<after>");
16
+ }
17
+ return { before: sides[0], after: sides[1] };
18
+ }
19
+ function parseTimeout(value) {
20
+ if (value === undefined)
21
+ return undefined;
22
+ const minutes = Number(value);
23
+ if (!Number.isFinite(minutes) || minutes <= 0 || minutes > 360) {
24
+ die("--timeout-minutes must be a number of minutes between 1 and 360");
25
+ }
26
+ return minutes;
27
+ }
6
28
  function reviewFlags(rest) {
7
29
  const text = (name) => rest.find((item) => item.startsWith(`--${name}=`))?.slice(name.length + 3);
8
30
  // `--remake-before-review` is the 0.4.13 spelling; both names mean the same
@@ -44,6 +66,8 @@ function reviewFlags(rest) {
44
66
  output,
45
67
  systemPromptFile: text("system-prompt-file"),
46
68
  systemPromptOverrideFile: text("system-prompt-override-file"),
69
+ range: parseRange(text("range")),
70
+ timeoutMinutes: parseTimeout(text("timeout-minutes")),
47
71
  };
48
72
  }
49
73
  const LOCAL_ONLY_FLAGS = new Set([
@@ -69,7 +93,9 @@ export function filterReviewConfigArgs(raw) {
69
93
  arg.startsWith("--remote-token=") ||
70
94
  arg.startsWith("--output=") ||
71
95
  arg.startsWith("--system-prompt-file=") ||
72
- arg.startsWith("--system-prompt-override-file=")) {
96
+ arg.startsWith("--system-prompt-override-file=") ||
97
+ arg.startsWith("--range=") ||
98
+ arg.startsWith("--timeout-minutes=")) {
73
99
  return false;
74
100
  }
75
101
  return true;
@@ -122,6 +148,15 @@ export async function parseReviewArgs(args) {
122
148
  if (flags.remoteByok !== undefined && !flags.remote) {
123
149
  die("--remote-byok requires --remote");
124
150
  }
151
+ if (flags.range && !flags.remote) {
152
+ die("--range requires --remote");
153
+ }
154
+ if (flags.timeoutMinutes !== undefined && !flags.range) {
155
+ die("--timeout-minutes requires --range");
156
+ }
157
+ if (flags.range && (flags.fresh || flags.toBranch)) {
158
+ die("--range cannot be used with --fresh or --to-branch");
159
+ }
125
160
  // `--json` must never prompt. `parseArgs` only receives the
126
161
  // filtered args, and `--json` is stripped before it sees them, so the flag
127
162
  // has to be applied here rather than after the parse returns.
@@ -7,6 +7,9 @@ export type Installation = {
7
7
  } | null;
8
8
  suspended_at: string | null;
9
9
  permissions?: Record<string, string>;
10
+ /** The webhook events this installation receives. `push` is here only when
11
+ * the owner turned it on in the App's settings. */
12
+ events?: string[];
10
13
  };
11
14
  /** App-level calls: list installations, mint an installation access token.
12
15
  * Not scoped to one installation — `AppClient` below is. */
@@ -27,6 +30,7 @@ export declare class AppClient implements GitHubClient {
27
30
  request<T>(endpoint: string): Promise<T>;
28
31
  pages<T>(endpoint: string, limit?: number, progress?: (page: number, fetched: number) => void): Promise<T[]>;
29
32
  write<T>(endpoint: string, body: unknown): Promise<T>;
33
+ patch<T>(endpoint: string, body: unknown): Promise<T>;
30
34
  createCheckRun<T>(endpoint: string, body: unknown): Promise<T>;
31
35
  updateCheckRun<T>(endpoint: string, body: unknown): Promise<T>;
32
36
  }
@@ -1,6 +1,8 @@
1
1
  import { githubFetch, httpError, paginate } from "./client.js";
2
2
  import { importAppPrivateKey, signAppJwt } from "./jwt.js";
3
- const API = "https://api.github.com";
3
+ import { getEnv } from "../util/runtime.js";
4
+ /** `CM_GITHUB_API_URL` points the App at a fake GitHub in the smoke tests. */
5
+ const API = (getEnv("CM_GITHUB_API_URL") ?? "https://api.github.com").replace(/\/+$/, "");
4
6
  function headers(token) {
5
7
  return {
6
8
  Accept: "application/vnd.github+json",
@@ -82,6 +84,13 @@ export class AppClient {
82
84
  body: JSON.stringify(body),
83
85
  });
84
86
  }
87
+ async patch(endpoint, body) {
88
+ return await call(endpoint, await this.app.installationToken(this.installationId), {
89
+ method: "PATCH",
90
+ headers: { "content-type": "application/json" },
91
+ body: JSON.stringify(body),
92
+ });
93
+ }
85
94
  async createCheckRun(endpoint, body) {
86
95
  return await this.write(endpoint, body);
87
96
  }
@@ -96,6 +96,46 @@ export const ENDPOINTS = [
96
96
  identities: APP_ONLY,
97
97
  feature: "Post a conversation comment",
98
98
  },
99
+ {
100
+ method: "POST",
101
+ pattern: "repos/{repo}/issues",
102
+ permission: "issues",
103
+ level: "write",
104
+ identities: APP_ONLY,
105
+ feature: "Open an issue for a P0 or P1 commit watch finding",
106
+ },
107
+ {
108
+ method: "GET",
109
+ pattern: "repos/{repo}/issues/{n}",
110
+ permission: "issues",
111
+ level: "read",
112
+ identities: APP_ONLY,
113
+ feature: "See whether a commit watch issue was closed",
114
+ },
115
+ {
116
+ method: "GET",
117
+ pattern: "repos/{repo}/collaborators/{name}/permission",
118
+ permission: "metadata",
119
+ level: "read",
120
+ identities: APP_ONLY,
121
+ feature: "Check a commenter has write access before acting on a comment",
122
+ },
123
+ {
124
+ method: "PATCH",
125
+ pattern: "repos/{repo}/issues/{n}",
126
+ permission: "issues",
127
+ level: "write",
128
+ identities: APP_ONLY,
129
+ feature: "Close a commit watch issue once its finding is fixed",
130
+ },
131
+ {
132
+ method: "POST",
133
+ pattern: "repos/{repo}/labels",
134
+ permission: "issues",
135
+ level: "write",
136
+ identities: APP_ONLY,
137
+ feature: "Create the co-maintainer and cm-P0 / cm-P1 labels",
138
+ },
99
139
  {
100
140
  method: "POST",
101
141
  pattern: "repos/{repo}/issues/{n}/reactions",
@@ -0,0 +1,7 @@
1
+ /** Who may steer co-maintainer from a comment. A webhook's
2
+ * author_association is only a first filter: MEMBER means a member of the
3
+ * organization and COLLABORATOR may be read-only, so the repository
4
+ * permission is asked from GitHub. */
5
+ import type { GitHubClient } from "../types.ts";
6
+ /** True when `login` can write to `repo`. Any error counts as no. */
7
+ export declare function hasWriteAccess(client: GitHubClient, repo: string, login: string | null | undefined): Promise<boolean>;
@@ -0,0 +1,12 @@
1
+ /** True when `login` can write to `repo`. Any error counts as no. */
2
+ export async function hasWriteAccess(client, repo, login) {
3
+ if (!login)
4
+ return false;
5
+ try {
6
+ const result = await client.request(`repos/${repo}/collaborators/${encodeURIComponent(login)}/permission`);
7
+ return ["admin", "maintain", "write"].includes(String(result.role_name ?? result.permission ?? ""));
8
+ }
9
+ catch {
10
+ return false;
11
+ }
12
+ }
@@ -2,6 +2,7 @@ import { runCommand } from "../pr/checkout.js";
2
2
  import { normalizeGithubRemote } from "./git_parse.js";
3
3
  import { stat } from "../util/runtime.js";
4
4
  import { CliError, EXIT_USAGE } from "../cli/error.js";
5
+ import { canonicalRepoName } from "../util/repo_name.js";
5
6
  export async function gitRoot(cwd, run = runCommand) {
6
7
  const result = await run("git", ["rev-parse", "--show-toplevel"], cwd);
7
8
  if (result.code !== 0) {
@@ -58,7 +59,7 @@ export async function detectRemoteRepo(cwd, override, run = runCommand) {
58
59
  if (!/^[^/]+\/[^/]+$/.test(override)) {
59
60
  throw new ReviewCliError("usage", "Repository must look like owner/repo");
60
61
  }
61
- return override;
62
+ return canonicalRepoName(override);
62
63
  }
63
64
  const remotes = await run("git", ["remote"], cwd);
64
65
  const names = remotes.stdout
@@ -78,7 +79,7 @@ export async function detectRemoteRepo(cwd, override, run = runCommand) {
78
79
  if (!normalized.ok) {
79
80
  throw new ReviewCliError("unsupported_host", "Only github.com remotes are supported for local review.");
80
81
  }
81
- return normalized.fullName;
82
+ return canonicalRepoName(normalized.fullName);
82
83
  }
83
84
  export async function currentBranch(cwd, override, run = runCommand) {
84
85
  if (override)
@@ -2,7 +2,7 @@ import type { Run } from "../pr/checkout.ts";
2
2
  import { type Revision } from "../review/revision.ts";
3
3
  import { type UntrackedWarning } from "./git_untracked.ts";
4
4
  /** Single-file unified patch when bulk `git diff` did not map a path. */
5
- export declare function perFileUnifiedPatch(cwd: string, base: string, path: string, run: Run): Promise<string>;
5
+ export declare function perFileUnifiedPatch(cwd: string, base: string, path: string, run: Run, to?: string): Promise<string>;
6
6
  export declare function mergeBase(cwd: string, baseRef: string, remote: string, run: Run): Promise<string>;
7
7
  export declare function resolveBaseRef(cwd: string, remote: string, toBranch: string | undefined, run: Run): Promise<{
8
8
  ref: string;
@@ -12,4 +12,7 @@ export type LocalRevisionBuild = {
12
12
  revision: Revision;
13
13
  warnings: UntrackedWarning[];
14
14
  };
15
- export declare function buildLocalRevision(cwd: string, mergeBaseSha: string, baseLabel: string, run: Run): Promise<LocalRevisionBuild>;
15
+ /** The diff from `mergeBaseSha` to the working tree, untracked files
16
+ * included. With `to`, the diff between two commits instead, which is what a
17
+ * push review sends: nothing in the working tree is part of a push. */
18
+ export declare function buildLocalRevision(cwd: string, mergeBaseSha: string, baseLabel: string, run: Run, to?: string): Promise<LocalRevisionBuild>;
@@ -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))
@@ -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,
@@ -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 {};