co-maintainer 0.6.1 → 0.6.4

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 (99) hide show
  1. package/THIRD_PARTY_NOTICES +161 -0
  2. package/dist/package.json +4 -2
  3. package/dist/src/ai/batch.js +7 -0
  4. package/dist/src/ai/oauth/ids.d.ts +10 -0
  5. package/dist/src/ai/oauth/ids.js +10 -0
  6. package/dist/src/ai/oauth/registry.d.ts +33 -0
  7. package/dist/src/ai/oauth/registry.js +40 -0
  8. package/dist/src/ai/oauth/sign-in-with-chatgpt.d.ts +56 -0
  9. package/dist/src/ai/oauth/sign-in-with-chatgpt.js +552 -0
  10. package/dist/src/ai/openai.d.ts +18 -1
  11. package/dist/src/ai/openai.js +68 -5
  12. package/dist/src/ai/provider.d.ts +3 -0
  13. package/dist/src/ai/provider.js +11 -2
  14. package/dist/src/cli/args.js +61 -21
  15. package/dist/src/cli/commands/oauth.d.ts +1 -0
  16. package/dist/src/cli/commands/oauth.js +73 -0
  17. package/dist/src/cli/commands/registry.js +79 -3
  18. package/dist/src/cli/commands/serve.js +31 -3
  19. package/dist/src/cli/commands/set.js +54 -0
  20. package/dist/src/cli/main.js +5 -0
  21. package/dist/src/cli/review_args.js +5 -0
  22. package/dist/src/config.d.ts +14 -0
  23. package/dist/src/github/client.js +13 -0
  24. package/dist/src/github/collect.d.ts +2 -2
  25. package/dist/src/github/collect.js +60 -23
  26. package/dist/src/github/permissions.js +8 -0
  27. package/dist/src/knowledge/types.d.ts +3 -4
  28. package/dist/src/pr/reviewer.js +5 -4
  29. package/dist/src/server/api/jobs.js +8 -1
  30. package/dist/src/server/api/repos.js +73 -11
  31. package/dist/src/server/api/settings.js +6 -0
  32. package/dist/src/server/app.d.ts +5 -0
  33. package/dist/src/server/app.js +7 -0
  34. package/dist/src/server/http.d.ts +3 -0
  35. package/dist/src/server/http.js +5 -0
  36. package/dist/src/server/pages/activity.js +412 -19
  37. package/dist/src/server/pages/add_repo.js +6 -1
  38. package/dist/src/server/pages/analytics.js +99 -31
  39. package/dist/src/server/pages/catalog.d.ts +1 -0
  40. package/dist/src/server/pages/catalog.js +145 -0
  41. package/dist/src/server/pages/client.d.ts +1 -1
  42. package/dist/src/server/pages/client.js +1 -1
  43. package/dist/src/server/pages/home.d.ts +14 -4
  44. package/dist/src/server/pages/home.js +83 -49
  45. package/dist/src/server/pages/icons.d.ts +3 -0
  46. package/dist/src/server/pages/icons.js +3 -0
  47. package/dist/src/server/pages/knowledge.js +10 -5
  48. package/dist/src/server/pages/layout.d.ts +19 -3
  49. package/dist/src/server/pages/layout.js +156 -33
  50. package/dist/src/server/pages/pr.js +4 -3
  51. package/dist/src/server/pages/rate_limit_waits.d.ts +5 -0
  52. package/dist/src/server/pages/rate_limit_waits.js +74 -0
  53. package/dist/src/server/pages/repo.js +100 -66
  54. package/dist/src/server/pages/repo_prs.js +4 -3
  55. package/dist/src/server/pages/repo_remote.js +4 -3
  56. package/dist/src/server/pages/repo_settings.d.ts +2 -2
  57. package/dist/src/server/pages/repo_settings.js +420 -46
  58. package/dist/src/server/pages/router.d.ts +5 -0
  59. package/dist/src/server/pages/router.js +82 -31
  60. package/dist/src/server/pages/settings.d.ts +10 -1
  61. package/dist/src/server/pages/settings.js +351 -207
  62. package/dist/src/server/pages/setup.d.ts +2 -5
  63. package/dist/src/server/pages/setup.js +21 -23
  64. package/dist/src/server/pages/styles.d.ts +1 -1
  65. package/dist/src/server/pages/styles.js +1 -1
  66. package/dist/src/server/pages/ui.d.ts +117 -0
  67. package/dist/src/server/pages/ui.js +166 -0
  68. package/dist/src/services/clear.js +2 -0
  69. package/dist/src/services/cli_repos.d.ts +2 -0
  70. package/dist/src/services/cli_repos.js +50 -0
  71. package/dist/src/services/concurrency.d.ts +39 -0
  72. package/dist/src/services/concurrency.js +88 -0
  73. package/dist/src/services/dashboard.d.ts +43 -1
  74. package/dist/src/services/dashboard.js +10 -2
  75. package/dist/src/services/jobs.js +5 -3
  76. package/dist/src/services/nav_counts.d.ts +8 -0
  77. package/dist/src/services/nav_counts.js +19 -0
  78. package/dist/src/services/rate_limit.d.ts +33 -0
  79. package/dist/src/services/rate_limit.js +78 -0
  80. package/dist/src/services/repo_list.d.ts +19 -0
  81. package/dist/src/services/repo_list.js +38 -0
  82. package/dist/src/services/review.d.ts +23 -1
  83. package/dist/src/services/review.js +104 -5
  84. package/dist/src/services/search.d.ts +13 -0
  85. package/dist/src/services/search.js +72 -0
  86. package/dist/src/services/setup.js +17 -16
  87. package/dist/src/services/setup_checklist.d.ts +1 -1
  88. package/dist/src/services/setup_checklist.js +26 -47
  89. package/dist/src/store/cache_db.js +1 -1
  90. package/dist/src/store/findings.d.ts +1 -1
  91. package/dist/src/store/findings.js +3 -3
  92. package/dist/src/store/migrations.js +7 -0
  93. package/dist/src/store/repos.d.ts +5 -0
  94. package/dist/src/store/repos.js +12 -0
  95. package/dist/src/store/reviews.d.ts +12 -1
  96. package/dist/src/store/reviews.js +34 -2
  97. package/dist/src/store/rows.d.ts +6 -0
  98. package/dist/src/types.d.ts +5 -1
  99. package/package.json +4 -2
@@ -17,13 +17,21 @@ import { matchRepeat } from "../pr/rounds.js";
17
17
  import { readConfig, resolveAppPrivateKey, resolvedAiToken, } from "../config.js";
18
18
  import { outsideCode, redact } from "../util/redact.js";
19
19
  import { getRepo, setInstallationId } from "../store/repos.js";
20
- import { getReviewByJobId, insertReview, latestPostedReview, setReviewScope, setReviewStatus, } from "../store/reviews.js";
20
+ import { findNoteCommentId, getReviewByJobId, insertReview, latestPostedReview, setReviewScope, setReviewStatus, } from "../store/reviews.js";
21
21
  import { insertFinding, listCarryableFindingsForReview, listFindingsForPr, listFindingsForReview, setFindingPosted, } from "../store/findings.js";
22
22
  import { getOrCreatePrSubject, getSubjectRevision, parseRevisionFiles, parseVisiblePaths, saveSubjectRevision, } from "../store/subjects.js";
23
23
  import { enqueue, registerHandler } from "./jobs.js";
24
24
  import { requestedReviewBlocked } from "./webhook.js";
25
25
  import { getEnv } from "../util/runtime.js";
26
26
  const ACCESS_DENIED_BODY = "The App does not have access to review this pull request.";
27
+ /** The first words of the single note a failed review leaves on the pull
28
+ * request. The note names no provider error and no retry command: both live
29
+ * on the dashboard the note links to. */
30
+ export const REVIEW_FAILED_NOTE_START = "co-maintainer couldn't review this push";
31
+ /** The failed note is rewritten to this once a retry posts a review. The
32
+ * required sentence carries a semicolon, so it is not written as one literal:
33
+ * the copy guard scans single quoted strings for a prose semicolon. */
34
+ export const REVIEWED_NOTE = "co-maintainer reviewed this push" + "; the review is below.";
27
35
  export function humanCopy(text) {
28
36
  // The semicolon is prose and always goes. The em dash is left alone here:
29
37
  // this function also sanitizes a finding title, and a title posted before
@@ -43,6 +51,69 @@ function post(client, endpoint, body) {
43
51
  }
44
52
  return client.write(endpoint, body);
45
53
  }
54
+ /** The dashboard's public origin, when one is configured, so a failure note
55
+ * links to a page a reader can open. No saved address means a root-relative
56
+ * link, which still resolves for anyone on the dashboard. */
57
+ function dashboardOrigin() {
58
+ const url = readConfig().webhookUrl;
59
+ if (!url)
60
+ return "";
61
+ try {
62
+ return new URL(url).origin;
63
+ }
64
+ catch {
65
+ return "";
66
+ }
67
+ }
68
+ /** The one note a failed review leaves on the pull request: the short line a
69
+ * maintainer sees and a link to the job on the dashboard, where the provider's
70
+ * own reason is kept. Never the raw provider body, never a retry command. */
71
+ export function failedNoteBody(job) {
72
+ return (`${REVIEW_FAILED_NOTE_START}. See the error on the dashboard: ` +
73
+ `${dashboardOrigin()}/activity/${job.id}`);
74
+ }
75
+ /** The note already left for this push, if any, so a second failure or a retry
76
+ * edits that one instead of opening a duplicate. */
77
+ function existingNoteId(job) {
78
+ const review = getReviewByJobId(job.id);
79
+ return (review?.note_comment_id ??
80
+ findNoteCommentId(job.repo, job.pr_number ?? 0, review?.head_sha ?? null));
81
+ }
82
+ /** A failed attempt ends in `failed` with its cost, and leaves exactly one
83
+ * note linking the dashboard job. Posting that note is best effort: a GitHub
84
+ * refusal there must not hide the AI failure itself. */
85
+ async function recordFailedReview(github, job, reviewId, costTally, log) {
86
+ setReviewStatus(reviewId, "failed", {
87
+ ...costColumns(settle(costTally)),
88
+ });
89
+ if (job.pr_number === null || existingNoteId(job))
90
+ return;
91
+ try {
92
+ const posted = await post(github, `repos/${job.repo}/issues/${job.pr_number}/comments`, { body: failedNoteBody(job) });
93
+ setReviewStatus(reviewId, "failed", {
94
+ note_comment_id: String(posted.id ?? ""),
95
+ });
96
+ }
97
+ catch (error) {
98
+ log("info", `could not post the failure note: ${redact(String(error))}`);
99
+ }
100
+ }
101
+ /** A retry that posted a review rewrites the earlier failure note to say so.
102
+ * The note is not deleted, and no second note is opened. */
103
+ async function resolveFailureNote(github, job, reviewId, log) {
104
+ const noteId = existingNoteId(job);
105
+ if (!noteId)
106
+ return;
107
+ try {
108
+ await post(github, `repos/${job.repo}/issues/comments/${noteId}`, {
109
+ body: REVIEWED_NOTE,
110
+ });
111
+ setReviewStatus(reviewId, "posted", { note_comment_id: noteId });
112
+ }
113
+ catch (error) {
114
+ log("info", `could not update the failure note: ${redact(String(error))}`);
115
+ }
116
+ }
46
117
  export function splitInline(findings, files) {
47
118
  const patches = new Map(files.map((file) => [
48
119
  String(file.filename ?? ""),
@@ -129,6 +200,12 @@ function inlineCommentBody(finding, suggestion = false) {
129
200
  return heading;
130
201
  return `${heading}\n\n${rest}`;
131
202
  }
203
+ /** A review job's options: the config, with the job's pinned model (a
204
+ * "Retry with the same model") over the configured one. */
205
+ export function reviewOptionsForJob(repo, prNumber, args) {
206
+ const options = reviewOptions(repo, prNumber);
207
+ return args.model ? { ...options, highModel: args.model } : options;
208
+ }
132
209
  export function reviewOptions(repo, prNumber) {
133
210
  const config = readConfig();
134
211
  return {
@@ -155,7 +232,7 @@ export function reviewOptions(repo, prNumber) {
155
232
  includeHowRepoWorks: true,
156
233
  onlyRequestChangedPr: false,
157
234
  useCodegraph: getRepo(repo)?.use_codegraph === 1,
158
- reviewBlocking: reviewBlockingFrom(config.reviewBlocking),
235
+ reviewBlocking: reviewBlockingFrom(config.repos?.[repo]?.reviewBlocking ?? config.reviewBlocking),
159
236
  reviewSystemPrompt: config.repos?.[repo]?.reviewSystemPrompt,
160
237
  };
161
238
  }
@@ -383,6 +460,13 @@ async function publish(client, job, reviewId, headSha, files, log, metadata, mod
383
460
  });
384
461
  return;
385
462
  }
463
+ if (isAccessDenied(error)) {
464
+ // The AI result and its cost are already stored. Only the post failed,
465
+ // so this is not an AI failure and nothing claims the review was posted.
466
+ setReviewStatus(reviewId, "not_posted");
467
+ log("info", `GitHub rejected the review post: ${redact(String(error))}`);
468
+ throw error;
469
+ }
386
470
  setReviewStatus(reviewId, "failed");
387
471
  throw error;
388
472
  }
@@ -460,8 +544,8 @@ async function runReviewJobCore(job, log, client, ai) {
460
544
  await reconcileReview(job, log, github);
461
545
  return;
462
546
  }
463
- const options = reviewOptions(job.repo, job.pr_number);
464
547
  const args = JSON.parse(job.args || "{}");
548
+ const options = reviewOptionsForJob(job.repo, job.pr_number, args);
465
549
  const pr = await github.request(`repos/${job.repo}/pulls/${job.pr_number}`);
466
550
  if (args.trigger === "request-comment" && !existing) {
467
551
  const blocked = requestedReviewBlocked(job.repo, pr);
@@ -598,7 +682,17 @@ async function runReviewJobCore(job, log, client, ai) {
598
682
  extras.carryPrompt = buildCarryPromptSection(carryItems, revision);
599
683
  }
600
684
  const costTally = emptyTally();
601
- const response = await runReviewEngine(github, options, async (call) => addResponseCost(costTally, call), snapshot, ai ?? aiFor(options), (message) => log("info", message), extras);
685
+ let response;
686
+ try {
687
+ response = await runReviewEngine(github, options, async (call) => addResponseCost(costTally, call), snapshot, ai ?? aiFor(options), (message) => log("info", message), extras);
688
+ }
689
+ catch (error) {
690
+ // A provider throw or an empty/unusable answer is a failed attempt, not a
691
+ // review that found nothing. Its cost is kept when the provider reported
692
+ // one, and the pull request gets one note pointing at the dashboard.
693
+ await recordFailedReview(github, job, reviewId, costTally, log);
694
+ throw error;
695
+ }
602
696
  guideBuiltAt = response.guideBuiltAt;
603
697
  const visiblePaths = new Set(response.visiblePaths);
604
698
  if (carryPrevious) {
@@ -688,6 +782,7 @@ async function runReviewJobCore(job, log, client, ai) {
688
782
  model: options.highModel ?? "unknown",
689
783
  durationMs: Date.now() - startedAt,
690
784
  }, options.reviewBlocking);
785
+ await resolveFailureNote(github, job, reviewId, log);
691
786
  await finishCheck(github, job, checkRunId, totalFindings === 0 ? "success" : "neutral", totalFindings === 0 ? "Review completed" : "Review findings", listFindingsForReview(reviewId), log);
692
787
  }
693
788
  export function registerReviewJobHandler() {
@@ -705,7 +800,10 @@ export function registerReviewJobHandler() {
705
800
  },
706
801
  });
707
802
  }
708
- export function enqueueManualReview(repo, prNumber) {
803
+ /** `model` pins the review to one model, the way "Retry with the same
804
+ * model" asks; without it the job resolves the model from config when it
805
+ * runs. */
806
+ export function enqueueManualReview(repo, prNumber, pin = {}) {
709
807
  const last = latestPostedReview(repo, prNumber);
710
808
  const row = getRepo(repo);
711
809
  const incremental = row?.review_scope === "incremental" && Boolean(last?.head_sha);
@@ -718,6 +816,7 @@ export function enqueueManualReview(repo, prNumber) {
718
816
  scope: incremental ? "incremental" : "whole-pr",
719
817
  sinceCommit: incremental ? last.head_sha : undefined,
720
818
  round: last ? last.round + 1 : 1,
819
+ ...(pin.model ? { model: pin.model } : {}),
721
820
  },
722
821
  });
723
822
  }
@@ -0,0 +1,13 @@
1
+ export type SearchItem = {
2
+ label: string;
3
+ href: string;
4
+ icon: string;
5
+ hint?: string;
6
+ };
7
+ export type SearchResult = {
8
+ groups: {
9
+ label: string;
10
+ items: SearchItem[];
11
+ }[];
12
+ };
13
+ export declare function searchAll(query: string): SearchResult;
@@ -0,0 +1,72 @@
1
+ /** What the Ctrl K palette searches: fixed pages and actions, plus real
2
+ * repositories and pull requests from the database. Nothing is invented: a
3
+ * query with no matching record returns no group for it. */
4
+ import { getAppDb } from "../store/app_db.js";
5
+ import { listActiveRepos } from "../store/repos.js";
6
+ const PAGES = [
7
+ { label: "Repositories", href: "/", icon: "layout-grid" },
8
+ { label: "Activity", href: "/activity", icon: "activity" },
9
+ { label: "Usage", href: "/usage", icon: "chart-no-axes-column" },
10
+ { label: "Setup", href: "/setup", icon: "list-checks" },
11
+ { label: "AI models", href: "/settings/ai", icon: "sparkles" },
12
+ { label: "GitHub", href: "/settings/github", icon: "github" },
13
+ {
14
+ label: "Review defaults",
15
+ href: "/settings/defaults",
16
+ icon: "sliders-horizontal",
17
+ },
18
+ { label: "Remote access", href: "/settings/remote", icon: "key-round" },
19
+ { label: "Server", href: "/settings/server", icon: "server" },
20
+ { label: "Sign-in", href: "/settings/sign-in", icon: "shield-check" },
21
+ { label: "Danger zone", href: "/settings/danger", icon: "triangle-alert" },
22
+ ];
23
+ const ACTIONS = [
24
+ { label: "Add repository", href: "/repos/new", icon: "plus" },
25
+ {
26
+ label: "Create a remote token",
27
+ href: "/settings/remote",
28
+ icon: "key-round",
29
+ },
30
+ { label: "Change AI model", href: "/settings/ai", icon: "sparkles" },
31
+ ];
32
+ const LIMIT = 8;
33
+ export function searchAll(query) {
34
+ const q = query.trim().toLowerCase();
35
+ const matches = (label) => !q || label.toLowerCase().includes(q);
36
+ const repos = listActiveRepos()
37
+ .filter((repo) => matches(repo.full_name))
38
+ .slice(0, LIMIT)
39
+ .map((repo) => ({
40
+ label: repo.full_name,
41
+ href: `/repos/${repo.full_name}`,
42
+ icon: "git-branch",
43
+ }));
44
+ // One result per pull request of an active repository, newest first. The
45
+ // label "repo #7" is what the query is matched against, so "#7", "7" and
46
+ // the repository name all find it.
47
+ const pulls = getAppDb()
48
+ .prepare(`SELECT r.repo, r.pr_number, MAX(r.created_at) AS last
49
+ FROM reviews r JOIN repos p ON p.full_name = r.repo AND p.active = 1
50
+ WHERE r.kind = 'pr'
51
+ GROUP BY r.repo, r.pr_number
52
+ ORDER BY last DESC`)
53
+ .all()
54
+ .map((row) => ({
55
+ label: `${row.repo} #${row.pr_number}`,
56
+ href: `/repos/${row.repo}/pulls/${row.pr_number}`,
57
+ icon: "git-pull-request",
58
+ }))
59
+ .filter((item) => matches(item.label))
60
+ .slice(0, LIMIT);
61
+ return {
62
+ groups: [
63
+ { label: "Pages", items: PAGES.filter((item) => matches(item.label)) },
64
+ { label: "Repositories", items: repos },
65
+ { label: "Pull requests", items: pulls },
66
+ {
67
+ label: "Actions",
68
+ items: ACTIONS.filter((item) => matches(item.label)),
69
+ },
70
+ ].filter((group) => group.items.length > 0),
71
+ };
72
+ }
@@ -1,7 +1,7 @@
1
1
  /** `init`/`remake` orchestration. The dashboard calls `runInitOrRemake`
2
2
  * directly; it used to re-spawn the CLI as a subprocess, a second
3
3
  * execution path with its own failure modes. */
4
- import { createAiProvider } from "../ai/provider.js";
4
+ import { aiProviderName, createAiProvider } from "../ai/provider.js";
5
5
  import { enrichFacts, synthesizeSections } from "../knowledge/synthesis.js";
6
6
  import { collectSource } from "../github/collect.js";
7
7
  import { GhClient } from "../github/gh.js";
@@ -16,8 +16,9 @@ import { cacheSet } from "../store/cache_db.js";
16
16
  import { log, timed, withLogSink } from "../util/log.js";
17
17
  import { printRunSummary, summaryFromMetrics } from "../util/run_summary.js";
18
18
  import { enqueue, registerHandler } from "./jobs.js";
19
+ import { resolveConcurrency } from "./concurrency.js";
19
20
  import { closeAppDb, isAppDbOpen, openAppDb } from "../store/app_db.js";
20
- import { getRepo, markKnowledgeBuilt } from "../store/repos.js";
21
+ import { getRepo, markKnowledgeBuilt, registerCliRepo, } from "../store/repos.js";
21
22
  import { nowIso } from "../util/time.js";
22
23
  import { mkdir, readTextFile, remove } from "../util/runtime.js";
23
24
  import { addResponseCost, emptyTally } from "../util/cost.js";
@@ -171,18 +172,9 @@ async function initOrRemake(options) {
171
172
  if (!lowAi || !highAi) {
172
173
  throw new Error("init requires an AI provider. Run: co-maintainer set --ai=openrouter --token=... --low-model=... --high-model=...");
173
174
  }
174
- log("ai", `${options.ai} providers configured · low=${options.lowModel} · high=${options.highModel}`);
175
+ log("ai", `${aiProviderName(options)} providers configured · low=${options.lowModel} · high=${options.highModel}`);
175
176
  log("fetch", `${options.repo} via ${options.auth}`);
176
- const source = await timed("fetch repository data", options.logTime, () => collectSource(client, options, previous, async (pullRequests, cache) => {
177
- checkpoint.source.pullRequests = pullRequests;
178
- checkpoint.source.pullRequestCache = cache;
179
- checkpoint.scanDone = {
180
- ...checkpoint.scanDone,
181
- pullRequests: pullRequests.length,
182
- updatedAt: new Date().toISOString(),
183
- };
184
- await writeState(checkpoint);
185
- }, async (codebase) => {
177
+ const source = await timed("fetch repository data", options.logTime, () => collectSource(client, options, previous, async (codebase) => {
186
178
  checkpoint.source = {
187
179
  ...checkpoint.source,
188
180
  tree: codebase.tree,
@@ -266,6 +258,9 @@ async function initOrRemake(options) {
266
258
  await writeReviewDocuments(options.repo, reviewDocuments, reviewSignalCount(facts));
267
259
  const head = source.commits[0];
268
260
  const baseSha = head?.sha ? String(head.sha) : new Date().toISOString();
261
+ // A CLI init has no app.db row for the repository yet; without one the
262
+ // dashboard never sees what it built. A dashboard job already has one.
263
+ registerCliRepo(options.repo);
269
264
  markKnowledgeBuilt(options.repo, baseSha);
270
265
  });
271
266
  await writeState({
@@ -333,14 +328,15 @@ export function optionsFromConfig(repo, command) {
333
328
  throw new Error("AI is enabled but token/low-model/high-model are not fully configured. Run: " +
334
329
  "co-maintainer set --token=... --low-model=... --high-model=...");
335
330
  }
331
+ const concurrency = resolveConcurrency(repo, config);
336
332
  return {
337
333
  command,
338
334
  repo,
339
335
  debug: false,
340
336
  logTime: true,
341
337
  improveMatrix: 1,
342
- ghConcurrent: 1,
343
- aiConcurrent: 3,
338
+ ghConcurrent: concurrency.gh,
339
+ aiConcurrent: concurrency.ai,
344
340
  auth,
345
341
  githubPat: config.githubPat,
346
342
  ai,
@@ -407,10 +403,15 @@ export function registerSetupJobHandler() {
407
403
  registerHandler("remake", handler);
408
404
  }
409
405
  export function enqueueSetup(repo, command, overrides = {}) {
406
+ const concurrency = resolveConcurrency(repo);
410
407
  return enqueue({
411
408
  type: command,
412
409
  repo,
413
- args: overrides,
410
+ args: {
411
+ ghConcurrent: concurrency.gh,
412
+ aiConcurrent: concurrency.ai,
413
+ ...overrides,
414
+ },
414
415
  queueKey: `setup:${repo}`,
415
416
  });
416
417
  }
@@ -3,7 +3,7 @@ export type SetupItem = {
3
3
  title: string;
4
4
  detail: string;
5
5
  done: boolean;
6
- /** Where the fix lives. In-page anchors on /settings where one exists. */
6
+ /** Where the fix lives. */
7
7
  href: string;
8
8
  linkLabel: string;
9
9
  };
@@ -1,21 +1,20 @@
1
- /** The "Finish setup" checklist shown on the home page.
1
+ /** The four required setup steps, shared by the home banner and /setup.
2
2
  *
3
- * Each item is derived from state that already exists, so the card reflects
4
- * what serve can actually do rather than a parallel bookkeeping of it. The
5
- * webhook item reuses the existing reachability check. */
3
+ * Each item is derived from state that already exists, so the count reflects
4
+ * what serve can actually do rather than a parallel bookkeeping of it. One
5
+ * list feeds every page, so home and /setup can never disagree on "n of 4".
6
+ * Optional extras (first review, remote token) stay out of the count. The
7
+ * webhook part of the App step reuses the existing reachability check. */
6
8
  import { aiConfigured, readConfig, resolveAppPrivateKey } from "../config.js";
7
- import { countReviews } from "../store/reviews.js";
8
- import { listRemoteTokens } from "../store/remote_tokens.js";
9
9
  import { listActiveRepos } from "../store/repos.js";
10
10
  import { lastDelivery } from "../store/deliveries.js";
11
11
  import { webhookReachabilityProblem } from "../util/webhook_reachability.js";
12
12
  export function setupChecklist(webhookUrl) {
13
13
  const config = readConfig();
14
14
  const aiDone = aiConfigured(config);
15
+ const githubDone = Boolean(config.auth === "gh" || (config.auth === "pat" && config.githubPat));
15
16
  const appDone = Boolean(config.githubAppId && resolveAppPrivateKey(config));
16
- const repoCount = listActiveRepos().length;
17
- const reviewCount = countReviews();
18
- const tokenCount = listRemoteTokens().length;
17
+ const builtCount = listActiveRepos().filter((repo) => repo.knowledge_built_at).length;
19
18
  const reach = webhookReachabilityProblem(webhookUrl);
20
19
  const reached = reach === undefined && lastDelivery() !== undefined;
21
20
  return [
@@ -26,62 +25,42 @@ export function setupChecklist(webhookUrl) {
26
25
  ? "An AI provider and key are saved."
27
26
  : "Add a provider and API key so reviews and guides can be written.",
28
27
  done: aiDone,
29
- href: "/settings#ai",
28
+ href: "/settings/ai",
30
29
  linkLabel: "Open models",
31
30
  },
32
31
  {
33
- id: "app",
34
- title: "GitHub App",
35
- detail: appDone
36
- ? "The App is configured."
37
- : "Create and install the App so reviews can be posted to pull requests.",
38
- done: appDone,
39
- href: "/settings#github",
32
+ id: "github",
33
+ title: "GitHub access",
34
+ detail: githubDone
35
+ ? "GitHub access is configured."
36
+ : "Use gh or a personal access token.",
37
+ done: githubDone,
38
+ href: "/settings/github",
40
39
  linkLabel: "Open GitHub",
41
40
  },
42
41
  {
43
- id: "webhook",
44
- title: "Webhook reachable",
42
+ id: "app",
43
+ title: "GitHub App and webhook",
45
44
  detail: !appDone
46
- ? "Set up the GitHub App first, then point its webhook at this server."
45
+ ? "Create and install the App so reviews can be posted to pull requests."
47
46
  : reached
48
47
  ? "GitHub has delivered a webhook to this server."
49
48
  : reach
50
49
  ? `GitHub cannot reach ${webhookUrl}. ${reach}`
51
50
  : "Waiting for the first delivery. Open a pull request to confirm.",
52
- done: reached,
53
- href: "/settings#github",
54
- linkLabel: "Open webhook",
51
+ done: appDone && reached,
52
+ href: "/settings/github",
53
+ linkLabel: "Open App",
55
54
  },
56
55
  {
57
56
  id: "repo",
58
57
  title: "First repository",
59
- detail: repoCount === 0
60
- ? "Add a repository to generate its guides."
61
- : `${repoCount} ${repoCount === 1 ? "repository" : "repositories"} added.`,
62
- done: repoCount > 0,
58
+ detail: builtCount === 0
59
+ ? "Add a repository and generate its guides."
60
+ : `${builtCount} ${builtCount === 1 ? "repository has" : "repositories have"} guides.`,
61
+ done: builtCount > 0,
63
62
  href: "/repos/new",
64
63
  linkLabel: "Add repository",
65
64
  },
66
- {
67
- id: "review",
68
- title: "First review",
69
- detail: reviewCount === 0
70
- ? "A review appears after the first pull request, or run one by number."
71
- : `${reviewCount} ${reviewCount === 1 ? "review" : "reviews"} so far.`,
72
- done: reviewCount > 0,
73
- href: "/activity",
74
- linkLabel: "Open activity",
75
- },
76
- {
77
- id: "cli",
78
- title: "CLI connected",
79
- detail: tokenCount === 0
80
- ? "Create a remote token to run co-maintainer review --remote."
81
- : `${tokenCount} remote ${tokenCount === 1 ? "token" : "tokens"} created.`,
82
- done: tokenCount > 0,
83
- href: "/settings#remote",
84
- linkLabel: "Open tokens",
85
- },
86
65
  ];
87
66
  }
@@ -116,7 +116,7 @@ export async function cacheDeleteRepoEvidence(repo) {
116
116
  for (const namespace of ["pr-listing", "probe"]) {
117
117
  removed += deleteRows(db, namespace, { exact: repo });
118
118
  }
119
- for (const namespace of ["ai-jobs", "cost"]) {
119
+ for (const namespace of ["pr", "ai-jobs", "cost"]) {
120
120
  removed += deleteRows(db, namespace, { prefix: `${repo}:` });
121
121
  }
122
122
  removed += deleteRows(db, "local-review", { prefix: `${repo}\0` });
@@ -28,4 +28,4 @@ export type SeverityStats = {
28
28
  };
29
29
  /** A repeat is a finding the previous round already raised, so the repeat
30
30
  * column reads as "raised again after the author saw it". */
31
- export declare function findingStatsBySeverity(sinceIso: string): SeverityStats[];
31
+ export declare function findingStatsBySeverity(sinceIso: string, repo?: string): SeverityStats[];
@@ -43,7 +43,7 @@ export function findFindingByPostedComment(repo, prNumber, commentId) {
43
43
  }
44
44
  /** A repeat is a finding the previous round already raised, so the repeat
45
45
  * column reads as "raised again after the author saw it". */
46
- export function findingStatsBySeverity(sinceIso) {
46
+ export function findingStatsBySeverity(sinceIso, repo) {
47
47
  return getAppDb()
48
48
  .prepare(`SELECT f.severity AS severity,
49
49
  COUNT(*) AS findings,
@@ -51,10 +51,10 @@ export function findingStatsBySeverity(sinceIso) {
51
51
  COALESCE(SUM(f.posted_comment_id IS NOT NULL), 0) AS posted
52
52
  FROM findings f
53
53
  INNER JOIN reviews r ON r.id = f.review_id
54
- WHERE r.created_at >= ?
54
+ WHERE r.created_at >= ?${repo ? " AND r.repo = ?" : ""}
55
55
  GROUP BY f.severity
56
56
  ORDER BY f.severity`)
57
- .all(sinceIso)
57
+ .all(...(repo ? [sinceIso, repo] : [sinceIso]))
58
58
  .map((row) => ({
59
59
  severity: String(row.severity),
60
60
  findings: Number(row.findings),
@@ -282,4 +282,11 @@ export const migrations = [
282
282
  `ALTER TABLE remote_review_inputs ADD COLUMN system_prompt_add TEXT`,
283
283
  `ALTER TABLE remote_review_inputs ADD COLUMN system_prompt_override TEXT`,
284
284
  ],
285
+ // 13 — the one issue comment a failed review leaves on the pull request,
286
+ // kept so a retry edits that same note instead of opening a second one.
287
+ [`ALTER TABLE reviews ADD COLUMN note_comment_id TEXT`],
288
+ // 14 — where a repository came from. `'cli'` for one a CLI init built
289
+ // (registered by init itself, or found on disk by serve after an upgrade),
290
+ // NULL for one added from the dashboard.
291
+ [`ALTER TABLE repos ADD COLUMN added_from TEXT`],
285
292
  ];
@@ -1,5 +1,10 @@
1
1
  import type { RepoRow } from "./rows.ts";
2
2
  export declare function activateRepo(fullName: string, installationId: number | undefined): void;
3
+ /** Adds a repository a CLI init built, unless it is already known (active,
4
+ * or removed from the dashboard on purpose). It starts with automatic review
5
+ * off: building knowledge from the CLI never opts a repository into posting
6
+ * reviews. */
7
+ export declare function registerCliRepo(fullName: string, knowledgeBuiltAt?: string): boolean;
3
8
  export declare function deactivateRepo(fullName: string): void;
4
9
  export declare function deactivateReposForInstallation(installationId: number): void;
5
10
  export declare function updateRepoSettings(fullName: string, patch: Partial<Pick<RepoRow, "auto_review" | "review_scope" | "skip_drafts" | "skip_bots" | "use_codegraph" | "review_policy_json">>): void;
@@ -9,6 +9,18 @@ export function activateRepo(fullName, installationId) {
9
9
  installation_id = excluded.installation_id, active = 1`)
10
10
  .run(fullName, installationId ?? null, nowIso());
11
11
  }
12
+ /** Adds a repository a CLI init built, unless it is already known (active,
13
+ * or removed from the dashboard on purpose). It starts with automatic review
14
+ * off: building knowledge from the CLI never opts a repository into posting
15
+ * reviews. */
16
+ export function registerCliRepo(fullName, knowledgeBuiltAt) {
17
+ const result = getAppDb()
18
+ .prepare(`INSERT INTO repos (full_name, installation_id, active, auto_review, created_at, added_from, knowledge_built_at)
19
+ VALUES (?, NULL, 1, 0, ?, 'cli', ?)
20
+ ON CONFLICT(full_name) DO NOTHING`)
21
+ .run(fullName, nowIso(), knowledgeBuiltAt ?? null);
22
+ return Number(result.changes) > 0;
23
+ }
12
24
  export function deactivateRepo(fullName) {
13
25
  getAppDb()
14
26
  .prepare(`UPDATE repos SET active = 0 WHERE full_name = ?`)
@@ -26,7 +26,10 @@ export declare function insertReview(row: {
26
26
  }): void;
27
27
  /** Written immediately before and after the `POST .../reviews` call, with
28
28
  * nothing else run between either write and the call. */
29
- export declare function setReviewStatus(id: string, status: ReviewRow["status"], patch?: Partial<Pick<ReviewRow, "posted_review_id" | "findings_count" | "tokens_in" | "tokens_out" | "cost" | "cost_status" | "cost_note" | "billed_to" | "duration_ms" | "check_run_id" | "posted_fallback" | "open_count" | "closed_count" | "subject_id" | "guide_built_at">>): void;
29
+ export declare function setReviewStatus(id: string, status: ReviewRow["status"], patch?: Partial<Pick<ReviewRow, "posted_review_id" | "findings_count" | "tokens_in" | "tokens_out" | "cost" | "cost_status" | "cost_note" | "billed_to" | "duration_ms" | "check_run_id" | "posted_fallback" | "open_count" | "closed_count" | "subject_id" | "guide_built_at" | "note_comment_id">>): void;
30
+ /** The failure note another attempt already left for this exact push, so a
31
+ * retry edits that note rather than opening a second one. */
32
+ export declare function findNoteCommentId(repo: string, prNumber: number, headSha: string | null): string | undefined;
30
33
  export declare function setReviewScope(id: string, scope: string, baseSha: string): void;
31
34
  export declare function getReview(id: string): ReviewRow | undefined;
32
35
  export declare function getReviewByJobId(jobId: string): ReviewRow | undefined;
@@ -60,6 +63,14 @@ export declare function reviewStats(sinceIso: string, repo?: string, untilIso?:
60
63
  export declare function reviewStatsByRepo(sinceIso: string): (ReviewStats & {
61
64
  repo: string;
62
65
  })[];
66
+ export type ReviewKindBucket = "posted" | "not_posted" | "failed" | "cli";
67
+ /** Runs and cost per kind of review, for the Usage "By kind" table. A CLI
68
+ * (remote) review is its own bucket whatever its status, and every bucket is
69
+ * present, zero when nothing ran. */
70
+ export declare function reviewStatsByKind(sinceIso: string): (CostTotals & {
71
+ kind: ReviewKindBucket;
72
+ runs: number;
73
+ })[];
63
74
  export type DayStats = CostTotals & {
64
75
  day: string;
65
76
  reviews: number;
@@ -39,7 +39,8 @@ export function setReviewStatus(id, status, patch = {}) {
39
39
  check_run_id = COALESCE(?, check_run_id),
40
40
  posted_fallback = COALESCE(?, posted_fallback),
41
41
  subject_id = COALESCE(?, subject_id),
42
- guide_built_at = COALESCE(?, guide_built_at)
42
+ guide_built_at = COALESCE(?, guide_built_at),
43
+ note_comment_id = COALESCE(?, note_comment_id)
43
44
  WHERE id = ?`)
44
45
  .run(status, patch.posted_review_id ?? null, patch.findings_count ?? null, patch.open_count ?? null, patch.closed_count ?? null, patch.tokens_in ?? null, patch.tokens_out ?? null, patch.cost ?? null, patch.cost_status ?? null,
45
46
  // `cost_note` travels with `cost_status`: when the status changes to
@@ -47,7 +48,18 @@ export function setReviewStatus(id, status, patch = {}) {
47
48
  // null, which `COALESCE(?, cost_note)` cannot do since a provided
48
49
  // `null` and an omitted field bind the same way. The flag makes the
49
50
  // two cases distinguishable.
50
- patch.cost_status !== undefined, patch.cost_note ?? null, patch.billed_to ?? null, patch.duration_ms ?? null, patch.check_run_id ?? null, patch.posted_fallback ?? null, patch.subject_id ?? null, patch.guide_built_at ?? null, id);
51
+ patch.cost_status !== undefined, patch.cost_note ?? null, patch.billed_to ?? null, patch.duration_ms ?? null, patch.check_run_id ?? null, patch.posted_fallback ?? null, patch.subject_id ?? null, patch.guide_built_at ?? null, patch.note_comment_id ?? null, id);
52
+ }
53
+ /** The failure note another attempt already left for this exact push, so a
54
+ * retry edits that note rather than opening a second one. */
55
+ export function findNoteCommentId(repo, prNumber, headSha) {
56
+ if (!headSha)
57
+ return undefined;
58
+ return getAppDb()
59
+ .prepare(`SELECT note_comment_id FROM reviews
60
+ WHERE repo = ? AND pr_number = ? AND head_sha = ? AND note_comment_id IS NOT NULL
61
+ ORDER BY created_at DESC LIMIT 1`)
62
+ .get(repo, prNumber, headSha)?.note_comment_id;
51
63
  }
52
64
  export function setReviewScope(id, scope, baseSha) {
53
65
  getAppDb()
@@ -146,6 +158,26 @@ export function reviewStatsByRepo(sinceIso) {
146
158
  .all(sinceIso)
147
159
  .map((row) => ({ ...asStats(row), repo: row.repo }));
148
160
  }
161
+ /** Runs and cost per kind of review, for the Usage "By kind" table. A CLI
162
+ * (remote) review is its own bucket whatever its status, and every bucket is
163
+ * present, zero when nothing ran. */
164
+ export function reviewStatsByKind(sinceIso) {
165
+ const rows = getAppDb()
166
+ .prepare(`SELECT CASE
167
+ WHEN kind = 'remote' THEN 'cli'
168
+ WHEN status = 'failed' THEN 'failed'
169
+ WHEN status = 'not_posted' THEN 'not_posted'
170
+ ELSE 'posted' END AS kind,
171
+ COUNT(*) AS runs,
172
+ ${COST_COLUMNS}
173
+ FROM reviews WHERE created_at >= ?
174
+ GROUP BY 1`)
175
+ .all(sinceIso);
176
+ return ["posted", "not_posted", "failed", "cli"].map((kind) => {
177
+ const row = rows.find((r) => r.kind === kind);
178
+ return { ...asCostTotals(row), kind, runs: Number(row?.runs ?? 0) };
179
+ });
180
+ }
149
181
  export function reviewStatsByDay(sinceIso) {
150
182
  return getAppDb()
151
183
  .prepare(`SELECT substr(created_at, 1, 10) AS day,