co-maintainer 0.6.13 → 0.7.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/README.md +1 -1
  2. package/dist/package.json +1 -1
  3. package/dist/src/ai/anthropic.js +2 -0
  4. package/dist/src/ai/batch.d.ts +3 -1
  5. package/dist/src/ai/batch.js +23 -2
  6. package/dist/src/ai/mermaid_loop.js +1 -1
  7. package/dist/src/ai/oauth/sign-in-with-chatgpt.js +8 -10
  8. package/dist/src/ai/openai.js +2 -0
  9. package/dist/src/ai/openrouter.js +2 -0
  10. package/dist/src/cli/args.js +47 -0
  11. package/dist/src/cli/command_json.d.ts +20 -1
  12. package/dist/src/cli/command_json.js +4 -0
  13. package/dist/src/cli/commands/config.d.ts +1 -1
  14. package/dist/src/cli/commands/config.js +1 -0
  15. package/dist/src/cli/commands/registry.js +226 -1
  16. package/dist/src/cli/commands/review.js +50 -9
  17. package/dist/src/cli/commands/serve.js +5 -0
  18. package/dist/src/cli/commands/set.js +70 -2
  19. package/dist/src/cli/commands/view.js +46 -5
  20. package/dist/src/cli/commands/view_sources.d.ts +11 -0
  21. package/dist/src/cli/commands/view_sources.js +40 -0
  22. package/dist/src/cli/main.js +5 -0
  23. package/dist/src/cli/pr_carry.d.ts +25 -0
  24. package/dist/src/cli/pr_carry.js +128 -0
  25. package/dist/src/cli/prompt.js +26 -1
  26. package/dist/src/cli/review_args.d.ts +8 -0
  27. package/dist/src/cli/review_args.js +18 -0
  28. package/dist/src/cli/review_carry.d.ts +32 -0
  29. package/dist/src/cli/review_carry.js +60 -0
  30. package/dist/src/cli/review_github.d.ts +16 -2
  31. package/dist/src/cli/review_github.js +49 -12
  32. package/dist/src/cli/review_intent.d.ts +25 -0
  33. package/dist/src/cli/review_intent.js +87 -0
  34. package/dist/src/cli/review_result.d.ts +53 -2
  35. package/dist/src/cli/review_result.js +90 -23
  36. package/dist/src/config.d.ts +27 -0
  37. package/dist/src/config.js +20 -12
  38. package/dist/src/extensions/command.d.ts +1 -0
  39. package/dist/src/extensions/command.js +355 -0
  40. package/dist/src/extensions/contexts.d.ts +65 -0
  41. package/dist/src/extensions/contexts.js +134 -0
  42. package/dist/src/extensions/cost.d.ts +8 -0
  43. package/dist/src/extensions/cost.js +6 -0
  44. package/dist/src/extensions/local_tracking.d.ts +7 -0
  45. package/dist/src/extensions/local_tracking.js +29 -0
  46. package/dist/src/extensions/mock.d.ts +29 -0
  47. package/dist/src/extensions/mock.js +67 -0
  48. package/dist/src/extensions/process.d.ts +43 -0
  49. package/dist/src/extensions/process.js +244 -0
  50. package/dist/src/extensions/registry.d.ts +79 -0
  51. package/dist/src/extensions/registry.js +240 -0
  52. package/dist/src/extensions/render_actions.d.ts +6 -0
  53. package/dist/src/extensions/render_actions.js +50 -0
  54. package/dist/src/extensions/render_cli.d.ts +18 -0
  55. package/dist/src/extensions/render_cli.js +88 -0
  56. package/dist/src/extensions/render_json.d.ts +51 -0
  57. package/dist/src/extensions/render_json.js +144 -0
  58. package/dist/src/extensions/render_markdown.d.ts +22 -0
  59. package/dist/src/extensions/render_markdown.js +96 -0
  60. package/dist/src/extensions/render_review.d.ts +44 -0
  61. package/dist/src/extensions/render_review.js +167 -0
  62. package/dist/src/extensions/report.d.ts +57 -0
  63. package/dist/src/extensions/report.js +97 -0
  64. package/dist/src/extensions/review_result.d.ts +2 -0
  65. package/dist/src/extensions/review_result.js +14 -0
  66. package/dist/src/extensions/run_folder.d.ts +74 -0
  67. package/dist/src/extensions/run_folder.js +172 -0
  68. package/dist/src/extensions/runner.d.ts +66 -0
  69. package/dist/src/extensions/runner.js +251 -0
  70. package/dist/src/extensions/schema.d.ts +103 -0
  71. package/dist/src/extensions/schema.js +539 -0
  72. package/dist/src/extensions/session.d.ts +56 -0
  73. package/dist/src/extensions/session.js +173 -0
  74. package/dist/src/github/collect.d.ts +7 -2
  75. package/dist/src/github/collect.js +66 -6
  76. package/dist/src/github/gh.d.ts +7 -0
  77. package/dist/src/github/gh.js +24 -29
  78. package/dist/src/knowledge/guide.js +3 -2
  79. package/dist/src/knowledge/instruction_files.d.ts +45 -0
  80. package/dist/src/knowledge/instruction_files.js +91 -0
  81. package/dist/src/knowledge/instructions.d.ts +78 -0
  82. package/dist/src/knowledge/instructions.js +280 -0
  83. package/dist/src/knowledge/rule_changes.d.ts +39 -0
  84. package/dist/src/knowledge/rule_changes.js +90 -0
  85. package/dist/src/knowledge/rules.d.ts +44 -0
  86. package/dist/src/knowledge/rules.js +82 -0
  87. package/dist/src/knowledge/synthesis.d.ts +1 -0
  88. package/dist/src/knowledge/synthesis.js +12 -5
  89. package/dist/src/knowledge/types.d.ts +4 -0
  90. package/dist/src/local/carry_over_store.d.ts +10 -0
  91. package/dist/src/local/carry_over_store.js +17 -0
  92. package/dist/src/local/review_local.js +100 -62
  93. package/dist/src/local/review_lock.js +15 -4
  94. package/dist/src/pr/diff_plan.d.ts +110 -0
  95. package/dist/src/pr/diff_plan.js +429 -0
  96. package/dist/src/pr/diff_summary.d.ts +17 -1
  97. package/dist/src/pr/diff_summary.js +87 -13
  98. package/dist/src/pr/review_diff.d.ts +47 -0
  99. package/dist/src/pr/review_diff.js +112 -0
  100. package/dist/src/pr/reviewer.d.ts +44 -19
  101. package/dist/src/pr/reviewer.js +114 -142
  102. package/dist/src/remote/client.js +67 -8
  103. package/dist/src/remote/http.d.ts +12 -0
  104. package/dist/src/remote/http.js +31 -0
  105. package/dist/src/remote/push_client.js +14 -3
  106. package/dist/src/remote/server/guides.js +12 -1
  107. package/dist/src/remote/server/routes.js +4 -2
  108. package/dist/src/remote/server/sessions.js +4 -1
  109. package/dist/src/remote/validate.js +11 -0
  110. package/dist/src/review/carry_over.d.ts +6 -1
  111. package/dist/src/review/carry_over.js +10 -2
  112. package/dist/src/review/coverage.d.ts +57 -0
  113. package/dist/src/review/coverage.js +186 -0
  114. package/dist/src/review/diagram.d.ts +73 -0
  115. package/dist/src/review/diagram.js +309 -0
  116. package/dist/src/review/engine.d.ts +2 -6
  117. package/dist/src/review/engine.js +1 -1
  118. package/dist/src/review/guides.d.ts +6 -0
  119. package/dist/src/review/guides.js +8 -1
  120. package/dist/src/review/intent.d.ts +24 -0
  121. package/dist/src/review/intent.js +28 -0
  122. package/dist/src/review/not_initialized.d.ts +13 -0
  123. package/dist/src/review/not_initialized.js +18 -0
  124. package/dist/src/review/system_prompt.d.ts +6 -0
  125. package/dist/src/review/system_prompt.js +13 -0
  126. package/dist/src/review/visible_paths.d.ts +22 -0
  127. package/dist/src/review/visible_paths.js +41 -0
  128. package/dist/src/server/pages/extensions.d.ts +5 -0
  129. package/dist/src/server/pages/extensions.js +72 -0
  130. package/dist/src/server/pages/pr.js +3 -2
  131. package/dist/src/services/dashboard.d.ts +8 -0
  132. package/dist/src/services/dashboard.js +8 -0
  133. package/dist/src/services/push_review.js +14 -5
  134. package/dist/src/services/remote_review.js +81 -26
  135. package/dist/src/services/replies.js +15 -8
  136. package/dist/src/services/review.d.ts +9 -3
  137. package/dist/src/services/review.js +109 -28
  138. package/dist/src/services/rules_build.d.ts +46 -0
  139. package/dist/src/services/rules_build.js +155 -0
  140. package/dist/src/services/setup.d.ts +31 -0
  141. package/dist/src/services/setup.js +120 -25
  142. package/dist/src/services/watch_comments.js +2 -0
  143. package/dist/src/store/cache_db.js +3 -0
  144. package/dist/src/store/extensions.d.ts +51 -0
  145. package/dist/src/store/extensions.js +132 -0
  146. package/dist/src/store/migrations.js +40 -0
  147. package/dist/src/types.d.ts +22 -1
  148. package/dist/src/util/atomic.d.ts +15 -1
  149. package/dist/src/util/atomic.js +59 -29
  150. package/dist/src/util/interrupt.d.ts +6 -0
  151. package/dist/src/util/interrupt.js +27 -0
  152. package/dist/src/util/runtime.d.ts +3 -1
  153. package/dist/src/util/runtime.js +2 -2
  154. package/dist/src/util/test_location_guard.d.ts +6 -0
  155. package/dist/src/util/test_location_guard.js +47 -0
  156. package/package.json +1 -1
@@ -0,0 +1,112 @@
1
+ import { pathsSeenInRound } from "../review/visible_paths.js";
2
+ import { coverageWarnings, } from "../review/coverage.js";
3
+ import { READ_FULL_DIFF_TOOL, readFullDiff, summarizeDiff, } from "./diff_summary.js";
4
+ import { coverageFromPlan, dropUntilFits, noDiffBlock, notShownBlock, planDiff, renderSection, restoreIntoRoom, } from "./diff_plan.js";
5
+ /** `fn` over `items` with at most `limit` calls running at once, results in
6
+ * input order. */
7
+ export async function mapWithLimit(items, limit, fn) {
8
+ const results = [];
9
+ let next = 0;
10
+ const worker = async () => {
11
+ while (next < items.length) {
12
+ const index = next++;
13
+ results[index] = await fn(items[index]);
14
+ }
15
+ };
16
+ const workers = Math.max(1, Math.min(Math.floor(limit) || 1, items.length));
17
+ await Promise.all(Array.from({ length: workers }, worker));
18
+ return results;
19
+ }
20
+ export async function prepareReviewDiff(input) {
21
+ const planned = planDiff(input.files);
22
+ const summarize = planned.filter((file) => file.state === "summarized");
23
+ const summaries = new Map();
24
+ const failed = [];
25
+ if (summarize.length > 0) {
26
+ // Built inside the try, so a provider that cannot be built fails each
27
+ // summary the same way a failed call does, and the review goes on.
28
+ let provider;
29
+ await mapWithLimit(summarize, input.concurrency, async (file) => {
30
+ try {
31
+ provider ??= input.summaryProvider();
32
+ const text = await summarizeDiff(file.path, file.patch, provider, input.usage);
33
+ if (!text)
34
+ throw new Error("the summary came back empty");
35
+ summaries.set(file.path, text);
36
+ input.report(`summarized large diff · ${file.path} · ${file.changes} changed lines`);
37
+ }
38
+ catch (error) {
39
+ // One failed summary must not fail the review. The model gets the
40
+ // start of the patch instead, the same as any other long file.
41
+ file.state = "partial";
42
+ failed.push(file.path);
43
+ input.report(`summary failed · ${file.path} · ${error instanceof Error ? error.message : String(error)}`);
44
+ }
45
+ });
46
+ }
47
+ const render = (file) => renderSection(file, {
48
+ tools: input.tools,
49
+ summary: summaries.get(file.path),
50
+ });
51
+ // The plan counted a fixed size per summary. The real ones, and any file
52
+ // that fell back to partial, may not fit, so check once more. Real
53
+ // summaries can also be shorter, which leaves room for a dropped file.
54
+ // Keyed by state too: a file restored from dropped renders differently
55
+ // from the summary it was measured as.
56
+ const rendered = new Map();
57
+ const textOf = (file) => {
58
+ const key = `${file.state}\0${file.path}`;
59
+ let text = rendered.get(key);
60
+ if (text === undefined) {
61
+ text = render(file);
62
+ rendered.set(key, text);
63
+ }
64
+ return text;
65
+ };
66
+ const sizeOf = (file) => textOf(file).length;
67
+ dropUntilFits(planned, sizeOf);
68
+ restoreIntoRoom(planned, sizeOf);
69
+ const sections = planned
70
+ .filter((file) => file.state !== "dropped" && !file.listed)
71
+ .map(textOf)
72
+ .join("\n\n");
73
+ const lists = [
74
+ noDiffBlock(planned),
75
+ notShownBlock(planned, { tools: input.tools }),
76
+ ]
77
+ .filter(Boolean)
78
+ .join("\n\n");
79
+ const readable = new Map(planned.map((file) => [
80
+ file.path,
81
+ { state: file.state, patch: file.patch },
82
+ ]));
83
+ const anyReadable = planned.some((file) => file.state === "partial" ||
84
+ file.state === "summarized" ||
85
+ file.state === "dropped");
86
+ const tools = anyReadable
87
+ ? [
88
+ {
89
+ name: "read-full-diff",
90
+ tool: READ_FULL_DIFF_TOOL,
91
+ run: (args) => readFullDiff(readable, args, input.readDiffMaxChars),
92
+ },
93
+ ]
94
+ : [];
95
+ const unchanged = input.unchangedPaths ?? [];
96
+ const coverage = coverageFromPlan(planned, unchanged);
97
+ // A file that fell back to partial and was then dropped is reported as
98
+ // dropped only.
99
+ const stillPartial = failed
100
+ .filter((path) => coverage.partial.includes(path))
101
+ .sort();
102
+ return {
103
+ sections,
104
+ notShown: lists,
105
+ diff: [sections, lists].filter(Boolean).join("\n\n"),
106
+ tools,
107
+ coverage,
108
+ warnings: coverageWarnings(coverage, input.catchesUp, stillPartial),
109
+ seenPaths: pathsSeenInRound(planned),
110
+ planned,
111
+ };
112
+ }
@@ -1,5 +1,6 @@
1
1
  import { type ToolHandler } from "../ai/mermaid_loop.ts";
2
2
  import type { Revision } from "../review/revision.ts";
3
+ import { type Coverage, type CoverageWarning } from "../review/coverage.ts";
3
4
  import type { Snapshot } from "./snapshot.ts";
4
5
  import type { AiProvider, AiResponse, GitHubClient, Json, Options } from "../types.ts";
5
6
  type UsageSink = (response: AiResponse) => Promise<void>;
@@ -12,42 +13,66 @@ export type ReviewExtras = {
12
13
  carryPrompt?: string;
13
14
  unchangedPaths?: string[];
14
15
  prepareCodegraphTools?: () => Promise<ToolHandler[]>;
16
+ /** The pull request and its files, already read by the caller. The review
17
+ * then makes neither request, so it judges what the caller stored. */
18
+ prefetched?: {
19
+ pull: Json;
20
+ files: Json[];
21
+ };
15
22
  /** The request's job name, `review_local` when left out. */
16
23
  job?: string;
24
+ /** Pull request files to review although the compare of this round does
25
+ * not list them: files an earlier round dropped or withheld and nobody
26
+ * touched since. A file the compare lists is not added twice. */
27
+ resend?: Json[];
28
+ /** The provider that summarizes large diffs. Left out, a low-model provider
29
+ * is built from the options. */
30
+ summaryAi?: AiProvider;
31
+ /** True when this mode's next run leaves out the files this run saw, so it
32
+ * sends the ones this run dropped. Only then do the warnings promise a
33
+ * later round. Left out, they do not. */
34
+ catchesUp?: boolean;
17
35
  };
36
+ /** What a review run returns to every flow. */
37
+ export type ReviewOutcome = AiResponse & {
38
+ /** The files the model received this round (`pathsSeenInRound`). A flow
39
+ * that saves a round saves them through `visiblePathsToSave`, which adds
40
+ * the files it skipped as unchanged. */
41
+ visiblePaths: string[];
42
+ guideBuiltAt: string | null;
43
+ codegraphState: "used" | "disabled" | "unavailable";
44
+ coverage: Coverage;
45
+ /** `diff_dropped`, `diff_withheld` and `summary_failed`. */
46
+ warnings: CoverageWarning[];
47
+ /** Every changed file of the subject, for the result's `revision` block. */
48
+ diffStats: {
49
+ files: number;
50
+ additions: number;
51
+ deletions: number;
52
+ };
53
+ };
54
+ /** Summaries run on the low model, whatever provider the caller handed in for
55
+ * the review itself. A server with no low model configured summarized with
56
+ * the review's provider before, and still does, so no review fails for it. */
57
+ export declare function summaryProvider(options: Options, reviewAi: AiProvider, report: ProgressSink, extras?: ReviewExtras): AiProvider;
18
58
  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.";
19
59
  /** Without tool support the model cannot read the Mermaid syntax docs, so
20
60
  * asking for a diagram only invites invented syntax. */
21
61
  export declare const NO_DIAGRAM_RULES = "Do not use Mermaid or any other diagram. Explain with prose only.";
22
- export declare function reviewSystemPrompt(diagrams: boolean): string;
62
+ export declare function reviewSystemPrompt(diagrams: boolean, options?: Options): string;
23
63
  /** The guide block every review sends, kept as the stable head of the system
24
64
  * prompt rather than the user prompt so a provider with prompt caching
25
65
  * (Anthropic's `cache_control`) reads it instead of re-billing it. Nothing
26
66
  * time-varying may enter this string — a single differing byte makes the cache
27
67
  * miss. */
28
- export declare function reviewGuidesBlock(guide: string, detailed: string, codebase: string): string;
68
+ export declare function reviewGuidesBlock(guide: string, detailed: string, codebase: string, instructions?: string): string;
29
69
  /** Shared PR and local/remote workspace review instructions: confirm claims
30
70
  * against the indexed graph, not only the diff slice. */
31
71
  export declare const CODEGRAPH_DIFF_VERIFICATION = "Examine the changes line by line, not just file by file. A single file can\ncontain more than one independent defect, and a change that looks fine in\nisolation can be wrong once you trace what calls it or what else it affects.\nWhen a finding depends on behavior outside the changed lines, confirm it with\ncodegraph-node, codegraph-callers, codegraph-callees, codegraph-impact, and\ncodegraph-affected before reporting it. Drop or correct findings that only seem\nplausible from the diff but contradict unchanged callers, callees, or the same\npattern elsewhere in the repo. Use those tools to check blast radius and whether\na test reaches the path. Do not guess coverage or impact from the diff alone\nwhen a tool can answer. A missing regression test is not a substitute for\nidentifying the concrete input or code path that misbehaves when you can.";
32
- /** GitHub omits `patch` entirely for files it considers too large, and the file
33
- * still appears in the compare response with only its counts. Rendering that as
34
- * an empty body reads as "this file did not change", and a reviewer then
35
- * reports the absence as a finding (a lockfile that was in fact regenerated,
36
- * say). Say plainly that the hunks are missing, and mark a per-file truncation
37
- * for the same reason. */
38
- export declare function filePatch(file: Json): string;
39
72
  export declare function clampToolRounds(totalDiffLines: number): number;
40
73
  export declare function clampImproveMatrix(matrix: number): number;
41
74
  export declare function readGuide(repo: string, name: string): Promise<string>;
42
75
  export type { Snapshot };
43
- export declare function reviewPullRequest(client: GitHubClient, options: Options, usage?: UsageSink, snapshot?: Snapshot, ai?: AiProvider, progress?: ProgressSink, extras?: ReviewExtras): Promise<AiResponse & {
44
- visiblePaths: string[];
45
- guideBuiltAt: string | null;
46
- codegraphState: "used" | "disabled" | "unavailable";
47
- }>;
76
+ export declare function reviewPullRequest(client: GitHubClient, options: Options, usage?: UsageSink, snapshot?: Snapshot, ai?: AiProvider, progress?: ProgressSink, extras?: ReviewExtras): Promise<ReviewOutcome>;
48
77
  /** Local workspace review — same prompt loop as PR review without GitHub. */
49
- export declare function reviewWorkspaceRevision(revision: Revision, options: Options, headSha: string, usage?: UsageSink, ai?: AiProvider, progress?: ProgressSink, extras?: ReviewExtras): Promise<AiResponse & {
50
- visiblePaths: string[];
51
- guideBuiltAt: string | null;
52
- codegraphState: "used" | "disabled" | "unavailable";
53
- }>;
78
+ export declare function reviewWorkspaceRevision(revision: Revision, options: Options, headSha: string, usage?: UsageSink, ai?: AiProvider, progress?: ProgressSink, extras?: ReviewExtras): Promise<ReviewOutcome>;
@@ -2,12 +2,20 @@ import { createAiProvider } from "../ai/provider.js";
2
2
  import { CliError, EXIT_USAGE } from "../cli/error.js";
3
3
  import { completeWithMermaidTools, } from "../ai/mermaid_loop.js";
4
4
  import { loadGuides } from "../review/guides.js";
5
+ import { notInitializedError } from "../review/not_initialized.js";
5
6
  import { computeScope } from "./scope.js";
6
7
  import { prepareCodegraphTools } from "./codegraph_tools.js";
7
8
  import { REVIEW_COPY_RULE, severitySection } from "./review_copy.js";
8
- import { reviewSystemPromptBlock } from "../review/system_prompt.js";
9
- import { needsSummary, READ_FULL_DIFF_TOOL, readFullDiff, summarizeDiff, } from "./diff_summary.js";
10
- import { numberPatch } from "./hunks.js";
9
+ import { repositoryInstructionsBlock, reviewSystemPromptBlock, } from "../review/system_prompt.js";
10
+ import { readDiffMaxChars } from "./diff_summary.js";
11
+ import { intentField, intentPromptNote } from "../review/intent.js";
12
+ import { mermaidToolFields, plantumlPromptRules, plantumlSystemRules, renderDiagrams, } from "../review/diagram.js";
13
+ import { diffFileFromGithub, diffFileFromRevision, } from "./diff_plan.js";
14
+ import { prepareReviewDiff } from "./review_diff.js";
15
+ import { coverageCounts, coverageTruncated, } from "../review/coverage.js";
16
+ import { readConfig } from "../config.js";
17
+ import { FakeAiProvider } from "../ai/fake.js";
18
+ import { getEnv } from "../util/runtime.js";
11
19
  import { FINDINGS_JSON_INSTRUCTIONS, FINDINGS_JSON_SCHEMA, findingsMarkdownFromJson, } from "./findings_json.js";
12
20
  import { aiProviderName } from "../ai/provider.js";
13
21
  /** One line naming the provider and the two models a review will call, printed
@@ -34,7 +42,41 @@ function requiredModel(model, label) {
34
42
  return model;
35
43
  throw new CliError("missing_model", `No ${label} model is configured.`, `Run co-maintainer set --${label}-model=..., or pass --${label}-model=... on the command that needs it.`, EXIT_USAGE);
36
44
  }
37
- const MAX_REVIEW_DIFF_CHARS = 240_000;
45
+ /** Summaries run on the low model, whatever provider the caller handed in for
46
+ * the review itself. A server with no low model configured summarized with
47
+ * the review's provider before, and still does, so no review fails for it. */
48
+ export function summaryProvider(options, reviewAi, report, extras) {
49
+ if (extras?.summaryAi)
50
+ return extras.summaryAi;
51
+ if (getEnv("CM_FAKE_AI") === "1")
52
+ return new FakeAiProvider();
53
+ if (!options.lowModel) {
54
+ report("no low model is configured · summaries use the review model");
55
+ return reviewAi;
56
+ }
57
+ return reviewProvider(options, options.lowModel, "low");
58
+ }
59
+ /** The listed files, then each of `resend` the list does not have. */
60
+ function withResent(listed, resend) {
61
+ if (!resend?.length)
62
+ return listed;
63
+ const names = new Set(listed.map((file) => String(file.filename ?? "")));
64
+ return [
65
+ ...listed,
66
+ ...resend.filter((file) => !names.has(String(file.filename ?? ""))),
67
+ ];
68
+ }
69
+ function diffStats(files) {
70
+ return {
71
+ files: files.length,
72
+ additions: files.reduce((sum, file) => sum + file.additions, 0),
73
+ deletions: files.reduce((sum, file) => sum + file.deletions, 0),
74
+ };
75
+ }
76
+ /** One progress line for the prepared diff, naming what did not go in whole. */
77
+ function diffReport(chars, coverage) {
78
+ return `diff prepared · ${chars} chars${coverageTruncated(coverage) ? ` · ${coverageCounts(coverage)}` : ""}`;
79
+ }
38
80
  export const MERMAID_GUIDANCE = `Mermaid selection and minimal syntax:
39
81
  flowchart = decisions, branches, pipelines, and fallback paths;
40
82
  swimlane-beta = work crossing owners, actors, services, teams, or layers;
@@ -82,16 +124,16 @@ clarifies most. Its type must be one of the types named in the system
82
124
  instructions. Keep labels short and grounded in the supplied evidence. A
83
125
  one-line fix or an obvious, single-step cause and effect genuinely needs no
84
126
  diagram. That is the only reason to omit one. Close every fenced block.`;
85
- export function reviewSystemPrompt(diagrams) {
127
+ export function reviewSystemPrompt(diagrams, options) {
86
128
  return `${REVIEW_ROLE}
87
- ${diagrams ? REVIEW_DIAGRAM_RULES : NO_DIAGRAM_RULES}`;
129
+ ${diagrams ? (plantumlSystemRules(options) ?? REVIEW_DIAGRAM_RULES) : NO_DIAGRAM_RULES}`;
88
130
  }
89
131
  /** The guide block every review sends, kept as the stable head of the system
90
132
  * prompt rather than the user prompt so a provider with prompt caching
91
133
  * (Anthropic's `cache_control`) reads it instead of re-billing it. Nothing
92
134
  * time-varying may enter this string — a single differing byte makes the cache
93
135
  * miss. */
94
- export function reviewGuidesBlock(guide, detailed, codebase) {
136
+ export function reviewGuidesBlock(guide, detailed, codebase, instructions = "") {
95
137
  return `REVIEW GUIDE:
96
138
  ${guide}
97
139
 
@@ -99,7 +141,7 @@ DETAILED GUIDE:
99
141
  ${detailed}
100
142
 
101
143
  CODEBASE CONVENTIONS:
102
- ${codebase || "None recorded."}`;
144
+ ${codebase || "None recorded."}${repositoryInstructionsBlock(instructions)}`;
103
145
  }
104
146
  /** Shared PR and local/remote workspace review instructions: confirm claims
105
147
  * against the indexed graph, not only the diff slice. */
@@ -114,12 +156,6 @@ pattern elsewhere in the repo. Use those tools to check blast radius and whether
114
156
  a test reaches the path. Do not guess coverage or impact from the diff alone
115
157
  when a tool can answer. A missing regression test is not a substitute for
116
158
  identifying the concrete input or code path that misbehaves when you can.`;
117
- function text(value, limit = 20_000) {
118
- const result = String(value ?? "");
119
- return result.length > limit
120
- ? `${result.slice(0, limit)}\n[truncated]`
121
- : result;
122
- }
123
159
  /** Turns a model reply into the Markdown every consumer already parses.
124
160
  * A reply that is not usable JSON is retried once with an
125
161
  * explicit reminder; if that also fails, the raw text is returned so the
@@ -147,33 +183,6 @@ async function normalizeReviewResponse(provider, request, response, extraTools,
147
183
  report("AI response was still not JSON, falling back to Markdown parsing");
148
184
  return response.text.trim();
149
185
  }
150
- const MAX_FILE_PATCH_CHARS = 12_000;
151
- /** GitHub omits `patch` entirely for files it considers too large, and the file
152
- * still appears in the compare response with only its counts. Rendering that as
153
- * an empty body reads as "this file did not change", and a reviewer then
154
- * reports the absence as a finding (a lockfile that was in fact regenerated,
155
- * say). Say plainly that the hunks are missing, and mark a per-file truncation
156
- * for the same reason. */
157
- export function filePatch(file) {
158
- const patch = String(file.patch ?? "");
159
- const status = String(file.status ?? "modified");
160
- const changes = Number(file.changes ?? 0);
161
- const additions = Number(file.additions ?? 0);
162
- const deletions = Number(file.deletions ?? 0);
163
- if (patch === "") {
164
- const counts = Number.isFinite(changes) && changes > 0
165
- ? `${changes} changed lines (+${additions} -${deletions})`
166
- : "an unreported number of changed lines";
167
- return (`[${status}: ${counts}, diff withheld by GitHub, not shown here. ` +
168
- `Do not treat this file as unchanged and do not report its contents.]`);
169
- }
170
- if (patch.length > MAX_FILE_PATCH_CHARS) {
171
- return (`${numberPatch(patch.slice(0, MAX_FILE_PATCH_CHARS))}\n[${status}: ${changes} ` +
172
- `changed lines total. This file's diff is cut off here, later hunks are ` +
173
- `not shown.]`);
174
- }
175
- return numberPatch(patch);
176
- }
177
186
  // Uncapped, a 100,000-line diff would ask for 1,000+ tool-loop rounds, each
178
187
  // able to spend multiple external calls.
179
188
  export function clampToolRounds(totalDiffLines) {
@@ -207,7 +216,8 @@ export async function reviewPullRequest(client, options, usage, snapshot, ai, pr
207
216
  report(modelSummary(options));
208
217
  report(`loading PR context for ${options.repo}#${number}`);
209
218
  const [pr, allComments, allReviews, guides] = await Promise.all([
210
- client.request(`repos/${options.repo}/pulls/${number}`),
219
+ extras?.prefetched?.pull ??
220
+ client.request(`repos/${options.repo}/pulls/${number}`),
211
221
  client.pages(`repos/${options.repo}/issues/${number}/comments`),
212
222
  client.pages(`repos/${options.repo}/pulls/${number}/reviews`),
213
223
  loadGuides(options.repo),
@@ -219,13 +229,15 @@ export async function reviewPullRequest(client, options, usage, snapshot, ai, pr
219
229
  const before = (item) => !snapshot || String(item.created_at ?? "") < snapshot.before;
220
230
  const comments = allComments.filter(before);
221
231
  const reviews = allReviews.filter(before);
222
- const files = snapshot
232
+ const listedFiles = snapshot
223
233
  ? ((await client.request(`repos/${options.repo}/compare/${snapshot.base ??
224
234
  String(pr.base?.ref ?? "main")}...${snapshot.commit}`)).files ?? [])
225
- : await client.pages(`repos/${options.repo}/pulls/${number}/files`);
235
+ : (extras?.prefetched?.files ??
236
+ (await client.pages(`repos/${options.repo}/pulls/${number}/files`)));
237
+ const files = withResent(listedFiles, extras?.resend);
226
238
  report(`diff files loaded · ${files.length} files`);
227
239
  if (!guide) {
228
- throw new Error(`repos/${options.repo}/PR_REVIEW_GUIDE.md was not found. Run init first`);
240
+ throw notInitializedError(options.repo);
229
241
  }
230
242
  if (options.debug) {
231
243
  console.log(`[debug] guides · short=${guide.length} chars · detailed=${detailed.length} chars · codebase=${codebase.length} chars`);
@@ -262,26 +274,20 @@ export async function reviewPullRequest(client, options, usage, snapshot, ai, pr
262
274
  if (scope) {
263
275
  report(`scope resolved · own=${ownFiles.length} files · upstream=${upstreamFiles.length} files`);
264
276
  }
265
- // Built only if needed, see reviewProvider.
266
- const filesNeedSummary = ownFiles.some(({ file }) => needsSummary(Number(file.changes ?? 0), String(file.patch ?? "")));
267
- const lowProvider = filesNeedSummary
268
- ? (ai ?? reviewProvider(options, options.lowModel, "low"))
269
- : undefined;
270
- const patchByPath = new Map();
271
- const [ownSections, codegraphTools] = await Promise.all([
272
- Promise.all(ownFiles.map(async ({ file, path }) => {
273
- const changes = Number(file.changes ?? 0);
274
- const patch = String(file.patch ?? "");
275
- if (!needsSummary(changes, patch)) {
276
- return `FILE: ${path}\n${filePatch(file)}`;
277
- }
278
- patchByPath.set(path, patch);
279
- const description = await summarizeDiff(path, patch, lowProvider, usage);
280
- report(`summarized large diff · ${path} · ${changes} changed lines`);
281
- return (`FILE: ${path}\n[${changes} changed lines, summarized below. ` +
282
- `call read-full-diff("${path}") for the complete diff if this is not ` +
283
- `enough]\n${description}`);
284
- })),
277
+ const provider = ai ?? reviewProvider(options, options.highModel, "high");
278
+ const diagrams = provider.supportsTools !== false;
279
+ const [prepared, codegraphTools] = await Promise.all([
280
+ prepareReviewDiff({
281
+ files: ownFiles.map(({ file }) => diffFileFromGithub(file)),
282
+ unchangedPaths: extras?.unchangedPaths,
283
+ catchesUp: extras?.catchesUp ?? false,
284
+ tools: diagrams,
285
+ concurrency: options.aiConcurrent,
286
+ readDiffMaxChars: readDiffMaxChars(readConfig().repos?.[options.repo]),
287
+ summaryProvider: () => summaryProvider(options, provider, report, extras),
288
+ usage,
289
+ report,
290
+ }),
285
291
  options.useCodegraph && headSha
286
292
  ? prepareCodegraphTools(options.repo, number, headSha, {
287
293
  allowInstall: options.allowToolInstall,
@@ -291,18 +297,7 @@ export async function reviewPullRequest(client, options, usage, snapshot, ai, pr
291
297
  if (options.useCodegraph) {
292
298
  report(`codegraph tools · ${codegraphTools.length > 0 ? "ready" : "unavailable"}`);
293
299
  }
294
- const extraTools = [
295
- ...codegraphTools,
296
- ...(patchByPath.size > 0
297
- ? [
298
- {
299
- name: "read-full-diff",
300
- tool: READ_FULL_DIFF_TOOL,
301
- run: (args) => readFullDiff(patchByPath, args),
302
- },
303
- ]
304
- : []),
305
- ];
300
+ const extraTools = [...codegraphTools, ...prepared.tools];
306
301
  // Bigger own-scope diffs need more codegraph round-trips to trace — fixed
307
302
  // at 3 rounds regardless of size caused the model to run out mid-review on
308
303
  // large PRs (verified via a tokio benchmark run: it hallucinated fake
@@ -310,9 +305,7 @@ export async function reviewPullRequest(client, options, usage, snapshot, ai, pr
310
305
  const totalDiffLines = ownFiles.reduce((sum, { file }) => sum + Number(file.changes ?? 0), 0);
311
306
  const maxToolRounds = clampToolRounds(totalDiffLines);
312
307
  report(`tool rounds · ${maxToolRounds} (own diff ${totalDiffLines} changed lines)`);
313
- const ownPatch = ownSections.join("\n\n");
314
- const diffWasTruncated = ownPatch.length > MAX_REVIEW_DIFF_CHARS;
315
- const ownDiff = text(ownPatch, MAX_REVIEW_DIFF_CHARS);
308
+ const ownDiff = prepared.diff;
316
309
  const unchangedListing = extras?.unchangedPaths?.length
317
310
  ? `\nUNCHANGED SINCE LAST REVIEW (paths only, do not re-report findings here):\n${extras.unchangedPaths
318
311
  .map((path) => `- ${path}`)
@@ -330,9 +323,7 @@ request. Do not raise a finding located only in this code. Only note an
330
323
  interaction if the pull request's own change above relies on or conflicts with
331
324
  one of these files, and never mark that finding blocking:
332
325
  ${upstreamListing}${unchangedListing}`;
333
- report(`diff prepared · ${ownPatch.length} chars${diffWasTruncated ? " · truncated for model context" : ""}`);
334
- const provider = ai ?? reviewProvider(options, options.highModel, "high");
335
- const diagrams = provider.supportsTools !== false;
326
+ report(diffReport(prepared.sections.length, prepared.coverage));
336
327
  const carryBlock = extras?.carryPrompt ? `${extras.carryPrompt}\n` : "";
337
328
  const prompt = `Review this pull request against the repository's review guide and
338
329
  codebase conventions. Find only actionable code-level violations supported by
@@ -363,7 +354,7 @@ Every diff line in the DIFF section starts with its line number in the new
363
354
  file. Copy "lineFrom" and "lineTo" from that column instead of counting from
364
355
  the @@ header. Removed lines have no number, so anchor a finding about removed
365
356
  code to the nearest numbered line.
366
- ${diagrams ? DIAGRAM_PROMPT_RULES : NO_DIAGRAM_RULES}
357
+ ${diagrams ? (plantumlPromptRules(options) ?? DIAGRAM_PROMPT_RULES) : NO_DIAGRAM_RULES}
367
358
  ${FINDINGS_JSON_INSTRUCTIONS}
368
359
 
369
360
  PULL REQUEST:
@@ -371,22 +362,24 @@ ${JSON.stringify({
371
362
  number,
372
363
  title: String(pr.title ?? ""),
373
364
  body: String(pr.body ?? ""),
365
+ ...intentField(options.reviewIntent),
374
366
  state: pr.state,
375
367
  changedFiles: files.map((file) => String(file.filename ?? "")),
376
368
  existingComments: comments.map((comment) => String(comment.body ?? "")),
377
369
  existingReviews: reviews.map((review) => String(review.body ?? "")),
378
- })}
370
+ })}${intentPromptNote(options.reviewIntent)}
379
371
 
380
372
  ${carryBlock}DIFF:
381
373
  ${diff}`;
382
374
  const matrix = clampImproveMatrix(options.improveMatrix);
383
375
  const request = {
384
376
  job: "review_pull_request",
385
- system: `${reviewSystemPrompt(diagrams)}\n\n${reviewGuidesBlock(guide, detailed, codebase)}${reviewSystemPromptBlock(options)}`,
377
+ system: `${reviewSystemPrompt(diagrams, options)}\n\n${reviewGuidesBlock(guide, detailed, codebase, guides.instructions)}${reviewSystemPromptBlock(options)}`,
386
378
  prompt,
387
379
  maxTokens: 24_000 * matrix,
388
380
  reasoningEffort: "high",
389
381
  responseFormat: FINDINGS_JSON_SCHEMA,
382
+ ...mermaidToolFields(options),
390
383
  };
391
384
  report(`AI request · ${options.ai} · model=${options.highModel ?? "unset"} · ` +
392
385
  `prompt=${prompt.length} chars · maxTokens=${request.maxTokens}`);
@@ -443,30 +436,21 @@ ${reviewText}`,
443
436
  console.log(`\n----- IMPROVED REVIEW ${pass - 1} -----\n${reviewText}\n`);
444
437
  }
445
438
  }
446
- const visiblePaths = ownFiles.map(({ path }) => path);
447
439
  return {
448
440
  ...response,
449
- text: `${severitySection()}\n${reviewText}`,
450
- visiblePaths,
441
+ text: `${severitySection()}\n${renderDiagrams(reviewText, options)}`,
442
+ visiblePaths: prepared.seenPaths,
451
443
  guideBuiltAt: guides.guideBuiltAt,
452
444
  codegraphState: !options.useCodegraph
453
445
  ? "disabled"
454
446
  : codegraphTools.length > 0
455
447
  ? "used"
456
448
  : "unavailable",
449
+ coverage: prepared.coverage,
450
+ warnings: prepared.warnings,
451
+ diffStats: diffStats(named.map(({ file }) => diffFileFromGithub(file))),
457
452
  };
458
453
  }
459
- function revisionToGithubFiles(revision) {
460
- return revision.files.map((file) => ({
461
- filename: file.path,
462
- status: file.status === "renamed" ? "renamed" : file.status,
463
- previous_filename: file.previousPath,
464
- additions: file.additions,
465
- deletions: file.deletions,
466
- changes: file.additions + file.deletions,
467
- patch: file.patch,
468
- }));
469
- }
470
454
  /** Local workspace review — same prompt loop as PR review without GitHub. */
471
455
  export async function reviewWorkspaceRevision(revision, options, headSha, usage, ai, progress, extras) {
472
456
  const report = progress ?? (() => { });
@@ -475,57 +459,40 @@ export async function reviewWorkspaceRevision(revision, options, headSha, usage,
475
459
  const { shortGuide, detailed, codebase, skill } = guides;
476
460
  const guide = shortGuide || skill;
477
461
  if (!guide) {
478
- throw new Error(`repos/${options.repo}/PR_REVIEW_GUIDE.md was not found. Run init first`);
462
+ throw notInitializedError(options.repo);
479
463
  }
480
- const files = revisionToGithubFiles(revision);
464
+ const files = revision.files.map((file) => diffFileFromRevision(file, revision.producer));
481
465
  const unchanged = new Set(extras?.unchangedPaths ?? []);
482
- const ownFiles = files
483
- .map((file) => ({
484
- file,
485
- path: String(file.filename ?? ""),
486
- }))
487
- .filter(({ path }) => !unchanged.has(path));
488
- const patchByPath = new Map();
489
- const ownSections = await Promise.all(ownFiles.map(async ({ file, path }) => {
490
- const changes = Number(file.changes ?? 0);
491
- const patch = String(file.patch ?? "");
492
- const lowProvider = needsSummary(changes, patch)
493
- ? (ai ?? reviewProvider(options, options.lowModel, "low"))
494
- : undefined;
495
- if (!lowProvider)
496
- return `FILE: ${path}\n${filePatch(file)}`;
497
- patchByPath.set(path, patch);
498
- const description = await summarizeDiff(path, patch, lowProvider, usage);
499
- return `FILE: ${path}\n[${changes} changed lines, summarized below]\n${description}`;
500
- }));
466
+ const ownFiles = files.filter(({ path }) => !unchanged.has(path));
467
+ const provider = ai ?? reviewProvider(options, options.highModel, "high");
468
+ const diagrams = provider.supportsTools !== false;
469
+ const prepared = await prepareReviewDiff({
470
+ files: ownFiles,
471
+ unchangedPaths: extras?.unchangedPaths,
472
+ catchesUp: extras?.catchesUp ?? false,
473
+ tools: diagrams,
474
+ concurrency: options.aiConcurrent,
475
+ readDiffMaxChars: readDiffMaxChars(readConfig().repos?.[options.repo]),
476
+ summaryProvider: () => summaryProvider(options, provider, report, extras),
477
+ usage,
478
+ report,
479
+ });
501
480
  const codegraphTools = options.useCodegraph
502
481
  ? extras?.prepareCodegraphTools
503
482
  ? await extras.prepareCodegraphTools()
504
483
  : await prepareCodegraphTools(options.repo, 0, headSha)
505
484
  : [];
506
- const extraTools = [
507
- ...codegraphTools,
508
- ...(patchByPath.size > 0
509
- ? [
510
- {
511
- name: "read-full-diff",
512
- tool: READ_FULL_DIFF_TOOL,
513
- run: (args) => readFullDiff(patchByPath, args),
514
- },
515
- ]
516
- : []),
517
- ];
518
- const totalDiffLines = ownFiles.reduce((sum, { file }) => sum + Number(file.changes ?? 0), 0);
485
+ const extraTools = [...codegraphTools, ...prepared.tools];
486
+ const totalDiffLines = ownFiles.reduce((sum, file) => sum + file.changes, 0);
519
487
  const maxToolRounds = clampToolRounds(totalDiffLines);
520
- const ownDiff = text(ownSections.join("\n\n"), MAX_REVIEW_DIFF_CHARS);
488
+ const ownDiff = prepared.diff;
489
+ report(diffReport(prepared.sections.length, prepared.coverage));
521
490
  const unchangedListing = extras?.unchangedPaths?.length
522
491
  ? `\nUNCHANGED SINCE LAST REVIEW (paths only):\n${extras.unchangedPaths
523
492
  .map((path) => `- ${path}`)
524
493
  .join("\n")}`
525
494
  : "";
526
495
  const carryBlock = extras?.carryPrompt ? `${extras.carryPrompt}\n` : "";
527
- const provider = ai ?? reviewProvider(options, options.highModel, "high");
528
- const diagrams = provider.supportsTools !== false;
529
496
  const prompt = `Review these local changes against the repository's review guide and
530
497
  codebase conventions. Find only actionable code-level violations supported by
531
498
  the diff and either the guide or the codebase conventions.
@@ -533,25 +500,27 @@ Do not invent low-value findings. If the diff contains a truncation marker or a
533
500
  file is summarized, limit claims to the supplied text and use read-full-diff or
534
501
  codegraph tools before asserting behavior outside what was shown.
535
502
  ${CODEGRAPH_DIFF_VERIFICATION}
536
- ${diagrams ? DIAGRAM_PROMPT_RULES : NO_DIAGRAM_RULES}
503
+ ${diagrams ? (plantumlPromptRules(options) ?? DIAGRAM_PROMPT_RULES) : NO_DIAGRAM_RULES}
537
504
  ${FINDINGS_JSON_INSTRUCTIONS}
538
505
 
539
506
  WORKSPACE:
540
507
  ${JSON.stringify({
541
508
  branch: revision.baseLabel,
509
+ ...intentField(revision.description),
542
510
  changedFiles: ownFiles.map(({ path }) => path),
543
- })}
511
+ })}${intentPromptNote(revision.description)}
544
512
 
545
513
  ${carryBlock}DIFF:
546
514
  ${ownDiff}${unchangedListing}`;
547
515
  const matrix = clampImproveMatrix(options.improveMatrix);
548
516
  const request = {
549
517
  job: extras?.job ?? "review_local",
550
- system: `${reviewSystemPrompt(diagrams)}\n\n${reviewGuidesBlock(guide, detailed, codebase)}${reviewSystemPromptBlock(options)}`,
518
+ system: `${reviewSystemPrompt(diagrams, options)}\n\n${reviewGuidesBlock(guide, detailed, codebase, guides.instructions)}${reviewSystemPromptBlock(options)}`,
551
519
  prompt,
552
520
  maxTokens: 24_000 * matrix,
553
521
  reasoningEffort: "high",
554
522
  responseFormat: FINDINGS_JSON_SCHEMA,
523
+ ...mermaidToolFields(options),
555
524
  };
556
525
  report(`AI request · prompt=${prompt.length} chars`);
557
526
  let response = await completeWithMermaidTools(provider, request, 1, extraTools, maxToolRounds);
@@ -590,9 +559,12 @@ ${reviewText}`,
590
559
  : "unavailable";
591
560
  return {
592
561
  ...response,
593
- text: `${severitySection()}\n${reviewText}`,
594
- visiblePaths: ownFiles.map(({ path }) => path),
562
+ text: `${severitySection()}\n${renderDiagrams(reviewText, options)}`,
563
+ visiblePaths: prepared.seenPaths,
595
564
  guideBuiltAt: guides.guideBuiltAt,
596
565
  codegraphState,
566
+ coverage: prepared.coverage,
567
+ warnings: prepared.warnings,
568
+ diffStats: diffStats(files),
597
569
  };
598
570
  }