co-maintainer 0.5.3 → 0.6.0

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 (38) hide show
  1. package/dist/package.json +1 -1
  2. package/dist/src/ai/batch.d.ts +19 -16
  3. package/dist/src/ai/batch.js +68 -46
  4. package/dist/src/cli/args.js +3 -2
  5. package/dist/src/cli/commands/registry.js +66 -17
  6. package/dist/src/cli/commands/set.js +102 -1
  7. package/dist/src/cli/review_args.d.ts +15 -0
  8. package/dist/src/cli/review_args.js +41 -1
  9. package/dist/src/config.d.ts +7 -0
  10. package/dist/src/github/collect.js +19 -1
  11. package/dist/src/knowledge/guide.d.ts +19 -4
  12. package/dist/src/knowledge/guide.js +222 -87
  13. package/dist/src/knowledge/skill.d.ts +4 -5
  14. package/dist/src/knowledge/skill.js +27 -35
  15. package/dist/src/knowledge/synthesis.d.ts +0 -13
  16. package/dist/src/knowledge/synthesis.js +176 -84
  17. package/dist/src/knowledge/types.d.ts +22 -0
  18. package/dist/src/local/review_local.js +4 -1
  19. package/dist/src/pr/reviewer.js +3 -2
  20. package/dist/src/remote/client.js +14 -1
  21. package/dist/src/remote/schema.d.ts +3 -0
  22. package/dist/src/remote/schema.js +3 -0
  23. package/dist/src/remote/validate.js +12 -1
  24. package/dist/src/review/system_prompt.d.ts +19 -0
  25. package/dist/src/review/system_prompt.js +34 -0
  26. package/dist/src/server/api/repos.js +56 -2
  27. package/dist/src/server/pages/client.d.ts +1 -1
  28. package/dist/src/server/pages/client.js +1 -1
  29. package/dist/src/server/pages/repo_settings.js +31 -0
  30. package/dist/src/services/remote_review.js +31 -2
  31. package/dist/src/services/review.js +2 -1
  32. package/dist/src/services/setup.js +63 -53
  33. package/dist/src/store/migrations.js +7 -0
  34. package/dist/src/store/remote_review_inputs.d.ts +2 -0
  35. package/dist/src/store/remote_review_inputs.js +3 -3
  36. package/dist/src/store/rows.d.ts +3 -0
  37. package/dist/src/types.d.ts +11 -0
  38. package/package.json +1 -1
@@ -19,40 +19,95 @@ function slug(value) {
19
19
  function promptText(value, limit = 6_000) {
20
20
  return value.length > limit ? `${value.slice(0, limit)}\n[truncated]` : value;
21
21
  }
22
+ function tryParse(value) {
23
+ try {
24
+ return JSON.parse(value);
25
+ }
26
+ catch {
27
+ return undefined;
28
+ }
29
+ }
30
+ /** Every balanced top-level `[...]` in the text, string-aware so a `[` inside a
31
+ * string does not shift the depth. */
32
+ function balancedArrays(text) {
33
+ const out = [];
34
+ let depth = 0;
35
+ let start = -1;
36
+ let inString = false;
37
+ let escape = false;
38
+ for (let index = 0; index < text.length; index++) {
39
+ const char = text[index];
40
+ if (inString) {
41
+ if (escape)
42
+ escape = false;
43
+ else if (char === "\\")
44
+ escape = true;
45
+ else if (char === '"')
46
+ inString = false;
47
+ continue;
48
+ }
49
+ if (char === '"')
50
+ inString = true;
51
+ else if (char === "[") {
52
+ if (depth === 0)
53
+ start = index;
54
+ depth++;
55
+ }
56
+ else if (char === "]" && depth > 0) {
57
+ depth--;
58
+ if (depth === 0 && start >= 0) {
59
+ out.push(text.slice(start, index + 1));
60
+ start = -1;
61
+ }
62
+ }
63
+ }
64
+ return out;
65
+ }
22
66
  function parseJson(text) {
23
67
  const cleaned = text
24
68
  .trim()
25
69
  .replace(/^```(?:json)?\s*/i, "")
26
70
  .replace(/\s*```$/, "");
27
- try {
28
- return JSON.parse(cleaned);
29
- }
30
- catch {
31
- const start = cleaned.indexOf("[");
32
- const end = cleaned.lastIndexOf("]");
33
- if (start < 0)
34
- throw new Error("AI fact output is not JSON");
35
- if (end > start)
36
- return JSON.parse(cleaned.slice(start, end + 1));
37
- const lastCompleteObject = cleaned.lastIndexOf("}");
38
- if (lastCompleteObject <= start) {
39
- throw new Error("AI fact output is truncated");
40
- }
41
- return JSON.parse(`${cleaned.slice(start, lastCompleteObject + 1)}]`);
71
+ const direct = tryParse(cleaned);
72
+ if (direct !== undefined)
73
+ return direct;
74
+ // The model sometimes appends a second array (for example `[]` then the real
75
+ // one), so the first-to-last-bracket slice is wrong. Read every balanced
76
+ // top-level array and prefer the first non-empty one.
77
+ const parsed = balancedArrays(cleaned)
78
+ .map((chunk) => tryParse(chunk))
79
+ .filter((value) => Array.isArray(value));
80
+ const nonEmpty = parsed.find((value) => value.length > 0);
81
+ if (nonEmpty)
82
+ return nonEmpty;
83
+ if (parsed.length)
84
+ return parsed[0];
85
+ // Last resort: repair an array whose final bracket was truncated.
86
+ // Nothing usable: return an empty list rather than throw. A format deviation
87
+ // must not cost the whole run.
88
+ const start = cleaned.indexOf("[");
89
+ if (start < 0)
90
+ return [];
91
+ const lastObject = cleaned.lastIndexOf("}");
92
+ if (lastObject > start) {
93
+ const repaired = tryParse(`${cleaned.slice(start, lastObject + 1)}]`);
94
+ if (repaired !== undefined)
95
+ return repaired;
42
96
  }
97
+ return [];
43
98
  }
44
99
  function factsFromResponse(text, evidence, defaultScope, origin) {
45
100
  const parsed = parseJson(text);
46
- if (!Array.isArray(parsed)) {
47
- throw new Error("AI fact output must be an array");
48
- }
101
+ if (!Array.isArray(parsed))
102
+ return [];
49
103
  return parsed.flatMap((item) => {
50
104
  if (!item || typeof item !== "object")
51
105
  return [];
52
106
  const value = item;
53
107
  const claim = String(value.claim ?? "").trim();
54
108
  const sectionKey = String(value.sectionKey ?? "").trim();
55
- if (!claim || !allowedSections.has(sectionKey))
109
+ const isReview = sectionKey === "review";
110
+ if (!claim || (!isReview && !allowedSections.has(sectionKey)))
56
111
  return [];
57
112
  const scope = value.scope === "current" ||
58
113
  value.scope === "repeated-history" ||
@@ -64,6 +119,14 @@ function factsFromResponse(text, evidence, defaultScope, origin) {
64
119
  value.confidence === "low"
65
120
  ? value.confidence
66
121
  : "medium";
122
+ // A review finding without an impact and an action is the generic advice
123
+ // that made the old guide hollow, so it is dropped rather than stored.
124
+ const impact = String(value.impact ?? "").trim();
125
+ const action = String(value.action ?? "").trim();
126
+ const location = String(value.location ?? "").trim();
127
+ const trigger = String(value.trigger ?? "").trim();
128
+ if (isReview && (!impact || !action))
129
+ return [];
67
130
  return [
68
131
  {
69
132
  id: `${sectionKey}:${slug(claim)}`,
@@ -75,6 +138,15 @@ function factsFromResponse(text, evidence, defaultScope, origin) {
75
138
  confidence,
76
139
  status: "active",
77
140
  origin,
141
+ ...(isReview
142
+ ? {
143
+ class: String(value.class ?? "general").trim() || "general",
144
+ ...(location ? { location } : {}),
145
+ ...(trigger ? { trigger } : {}),
146
+ impact,
147
+ action,
148
+ }
149
+ : {}),
78
150
  },
79
151
  ];
80
152
  });
@@ -121,18 +193,34 @@ function pullRequestUnit(pr) {
121
193
  body: promptText(pr.body),
122
194
  labels: pr.labels,
123
195
  comments: pr.comments.map((comment) => promptText(comment, 2_000)),
196
+ reviewComments: pr.reviewComments.map((comment) => promptText(comment, 2_000)),
124
197
  reviews: pr.reviews.map((review) => promptText(review, 2_000)),
125
198
  changedFiles: pr.changedFiles,
126
199
  diff: promptText(pr.diff, 8_000),
127
200
  });
128
201
  }
129
202
  function queueFor(provider, repo, ai, model, concurrency, validate) {
130
- return new AiBatch(provider, repo, Math.max(1, concurrency), `${ai}:v2:${model}`, validate);
203
+ return new AiBatch(provider, repo, Math.max(1, concurrency), `${ai}:v3:${model}`, validate);
131
204
  }
132
205
  /** `factsFromResponse` as a validator: `null` when the text parses into facts,
133
206
  * otherwise the parse error's message. Used so an unparseable response is never
134
207
  * cached. */
208
+ /** Whether the response contains a parseable JSON array at all. `parseJson`
209
+ * returns `[]` for anything it cannot read, so this is the only way to tell an
210
+ * empty-but-valid answer from garbage that must not be cached as a result. */
211
+ function hasJsonArray(text) {
212
+ const cleaned = text
213
+ .trim()
214
+ .replace(/^```(?:json)?\s*/i, "")
215
+ .replace(/\s*```$/, "");
216
+ if (Array.isArray(tryParse(cleaned)))
217
+ return true;
218
+ return balancedArrays(cleaned).some((chunk) => Array.isArray(tryParse(chunk)));
219
+ }
135
220
  function validateFacts(response, evidence, defaultScope) {
221
+ if (!hasJsonArray(response.text)) {
222
+ return `${evidence}: AI fact output is not a JSON array`;
223
+ }
136
224
  try {
137
225
  factsFromResponse(response.text, evidence, defaultScope, "repository");
138
226
  return null;
@@ -142,40 +230,29 @@ function validateFacts(response, evidence, defaultScope) {
142
230
  return `${evidence}: ${message}`;
143
231
  }
144
232
  }
145
- /** `validSection` as a validator: `null` when the section body is usable,
146
- * otherwise a short reason. A section that is empty or malformed is retried
147
- * once and then left uncached, so a later `sync` does not replay it. */
148
- function validateSection(response, key) {
149
- const section = cleanSection(response.text, key);
150
- if (!validSection(section, key)) {
151
- return "synthesis output is not a valid section";
152
- }
153
- return null;
154
- }
155
233
  function extractRequest(prompt, maxTokens) {
156
234
  return {
157
235
  job: "extract_unit",
158
236
  prompt,
159
237
  maxTokens,
160
- // Pulling facts out of a text needs no thinking, and on a thinking model
161
- // the thinking used the whole limit and left the answer empty.
162
- reasoningEffort: "none",
163
- system: "Extract only repository-specific facts. Never invent files, commands, or process.",
238
+ // Reading a discussion into structured findings is multi-step work: with no
239
+ // thinking the model returned an empty array for most pull requests, so a
240
+ // little reasoning is allowed (the answer still fits the token budget).
241
+ reasoningEffort: "low",
242
+ system: 'Extract only repository-specific facts and review findings. Never invent files, commands, or process. Never write a pull-request number, a commit id, a reviewer name, or quoted comment text in a claim. A review finding (sectionKey "review") states a concrete rule with an impact and an action.',
164
243
  };
165
244
  }
166
245
  function cleanSection(text, key) {
167
- const clean = text.replace(/^\s*```[a-zA-Z0-9_-]*\s*$/gm, "").trim();
168
- const heading = sectionTitles[key] ?? key;
169
- return clean.replace(/^##\s+.+$/m, `## ${heading}`);
170
- }
171
- function validSection(text, key) {
246
+ const clean = text
247
+ .replace(/^\s*```[a-zA-Z0-9_-]*\s*$/gm, "")
248
+ .replace(/```/g, "")
249
+ .trim();
172
250
  const heading = `## ${sectionTitles[key] ?? key}`;
173
- const bullets = text.match(/^-\s+/gm) ?? [];
174
- return (text.startsWith(heading) &&
175
- bullets.length > 0 &&
176
- bullets.length <= 6 &&
177
- !text.includes("```") &&
178
- !/\b(?:TODO|TBD)\b/i.test(text));
251
+ // Guarantee the heading the skill assembler keys on, and keep whatever body
252
+ // the model produced rather than rejecting it.
253
+ if (/^##\s+.+$/m.test(clean))
254
+ return clean.replace(/^##\s+.+$/m, heading);
255
+ return clean ? `${heading}\n\n${clean}` : heading;
179
256
  }
180
257
  function sectionGoal(key) {
181
258
  const goals = {
@@ -210,22 +287,26 @@ function synthesisFacts(facts, key) {
210
287
  .slice(0, 20));
211
288
  }
212
289
  export async function extractAiFacts(provider, repo, source, options, usage) {
213
- return (await extractAiFactsWithReport(provider, repo, source, options, usage)).facts;
214
- }
215
- export async function extractAiFactsWithReport(provider, repo, source, options, usage) {
216
290
  const requests = [];
217
291
  const evidence = [];
218
292
  const scopes = [];
219
293
  const prs = options.includePullRequests ? source.pullRequests : [];
220
294
  for (const pr of prs) {
221
- requests.push(extractRequest(`Analyze this pull request and return only a JSON array of atomic observations. Each item must have exactly:
222
- {"sectionKey":"one allowed section","claim":"one directly evidenced observation","scope":"historical-example","confidence":"medium"}
223
- Allowed sections: ${[...allowedSections].join(", ")}
224
- Use evidence from this PR only. Do not generalize this PR into a repository-wide policy.
225
- Return at most 6 items. Keep each claim under 180 characters. Do not explain the answer.
295
+ requests.push(extractRequest(`Analyze this pull request's reviews, comments, code and diff, and return only a JSON array of review findings.
296
+ Each item must have exactly:
297
+ {"sectionKey":"review","class":"a short area name","claim":"the invariant a reviewer would enforce, imperative and general","location":"path or path:line the finding is about, or empty when none","trigger":"the diff surface that should trigger this rule: a path, glob, or symbol, or empty when none","impact":"why this matters here, from the review's reasoning","action":"what to change or verify","scope":"historical-example","confidence":"medium"}
298
+ Rules:
299
+ - Include only substantive findings: a reviewer identifies something to fix, change, verify or decide.
300
+ - Never write an approval, a merge, "LGTM", thanks, a reviewer name, a pull-request number, a commit id, or quoted comment text.
301
+ - The claim is a general invariant, not one past fix: "When X changes, Y must also change", or "Every Z uses W", never "change this one line".
302
+ - trigger is what a reviewer can see in a diff: a path, a glob, or a symbol. It is how the rule applies to a future change, so a rule with no trigger is a one-off and is not useful.
303
+ - impact and action are mandatory and concrete. Paraphrase the reviewer's reasoning for impact; never quote it.
304
+ - class is a short area label chosen from a small, consistent set; reuse the same label for findings of the same kind so related findings can be grouped.
305
+ - location is a repository path when the review names one, otherwise leave it empty.
306
+ - Return every distinct finding the reviews support, not a summary. Do not explain the answer.
226
307
 
227
308
  PULL REQUEST:
228
- ${pullRequestUnit(pr)}`, 1_200));
309
+ ${pullRequestUnit(pr)}`, 2_400));
229
310
  evidence.push(`PR #${pr.number}`);
230
311
  scopes.push("historical-example");
231
312
  }
@@ -267,29 +348,33 @@ ${files}`, 2_200));
267
348
  const response = responses[index];
268
349
  if (!response)
269
350
  continue;
270
- try {
271
- facts.push(...factsFromResponse(response.text, evidence[index], scopes[index] ?? "historical-example", evidence[index] === "repository files"
272
- ? "repository"
273
- : "pull-request").filter((item) => !hasUnsupportedIdentifier(item.claim, source) &&
274
- !hasUnsupportedPath(item.claim, source) &&
275
- (evidence[index] !== "repository files" ||
276
- allowsContributionSections(source) ||
277
- !["title-body", "labels", "review-bar", "process"].includes(item.sectionKey))));
278
- }
279
- catch (error) {
280
- console.log(`[ai] invalid ${evidence[index]} output skipped: ${String(error)}`);
281
- }
351
+ facts.push(...factsFromResponse(response.text, evidence[index], scopes[index] ?? "historical-example", evidence[index] === "repository files" ? "repository" : "pull-request").filter((item) => {
352
+ if (hasUnsupportedIdentifier(item.claim, source) ||
353
+ hasUnsupportedPath(item.claim, source)) {
354
+ return false;
355
+ }
356
+ if (evidence[index] === "repository files" &&
357
+ !allowsContributionSections(source) &&
358
+ ["title-body", "labels", "review-bar", "process"].includes(item.sectionKey)) {
359
+ return false;
360
+ }
361
+ // An invented path is worse than no path: keep the finding and drop
362
+ // the location when it does not exist in the repository. The location
363
+ // may carry a line (`path:12` or `path:12-20`), which is stripped
364
+ // before the path is checked so a real path with a line survives.
365
+ if (item.sectionKey === "review" && item.location) {
366
+ const locationPath = item.location.replace(/:\d+(?:-\d+)?$/, "");
367
+ if (hasUnsupportedPath(locationPath, source)) {
368
+ item.location = undefined;
369
+ }
370
+ }
371
+ return true;
372
+ }));
282
373
  if (index % 10 === 0 || index === responses.length - 1) {
283
374
  console.log(`[ai] extract units ${index + 1}/${responses.length}`);
284
375
  }
285
376
  }
286
- return { facts, skipped: queue.skippedUnits() };
287
- }
288
- /** Same as {@link extractAiFacts}, but also reports what the batch skipped so
289
- * the caller can put it in the final `[done]` line. */
290
- export async function enrichFactsWithReport(provider, repo, base, source, options, usage) {
291
- const { facts, skipped } = await extractAiFactsWithReport(provider, repo, source, options, usage);
292
- return { facts: mergeFacts(base, facts), skipped };
377
+ return facts;
293
378
  }
294
379
  function mergeFacts(base, extra) {
295
380
  const merged = new Map(base.map((item) => [item.id, { ...item, evidence: [...item.evidence] }]));
@@ -313,18 +398,21 @@ export async function synthesizeSections(provider, repo, facts, _previousMarkdow
313
398
  const requests = [];
314
399
  const keys = [];
315
400
  for (const key of [...new Set(facts.map((item) => item.sectionKey))]) {
401
+ // Review findings are the guide's material, not a prose section.
402
+ if (!sectionTitles[key])
403
+ continue;
316
404
  if (onlySections && !onlySections.has(key))
317
405
  continue;
318
406
  const relevant = synthesisFacts(facts, key);
319
407
  // A section whose only facts came from a single pull request has no
320
- // repository policy to synthesize, so it is left to the deterministic
321
- // renderer instead of asking the model for an empty answer.
408
+ // repository policy to synthesize, so it is skipped instead of asking the
409
+ // model for an empty answer.
322
410
  if (!relevant.length)
323
411
  continue;
324
412
  keys.push(key);
325
413
  requests.push({
326
414
  job: "synth_section",
327
- maxTokens: 1_800,
415
+ maxTokens: 4_000,
328
416
  reasoningEffort: "high",
329
417
  system: `You synthesize contribution guidance for an unfamiliar open-source repository.
330
418
  Help developers make correct implementation, testing, review, debugging, and release
@@ -357,17 +445,21 @@ FACTS:
357
445
  ${JSON.stringify(relevant)}`,
358
446
  });
359
447
  }
360
- const queue = queueFor(provider, repo, ai, model, concurrency, (request, response) => validateSection(response, keys[requests.indexOf(request)] ?? ""));
448
+ // No validator: a section that does not match the ideal shape is normalized
449
+ // by `cleanSection` and kept, not rejected. Losing the whole run over a
450
+ // section's format is not worth it.
451
+ const queue = queueFor(provider, repo, ai, model, concurrency);
361
452
  const responses = await queue.run(requests, usage);
362
- // A section that the batch skipped has no response, and a unit that failed
363
- // validation never produces one: omit those keys entirely rather than
364
- // passing an empty string, so `assembleSkill` keeps its own content for them
365
- // (an empty string is a *present* override and would blank the section).
453
+ // A heading with no bullets is the model saying "no durable guidance", so the
454
+ // section is omitted rather than written empty. Anything with a bullet is
455
+ // kept as the model wrote it.
366
456
  const overrides = {};
367
457
  responses.forEach((response, index) => {
368
- const section = response ? cleanSection(response.text, keys[index]) : "";
369
- if (validSection(section, keys[index]))
458
+ if (!response)
459
+ return;
460
+ const section = cleanSection(response.text, keys[index]);
461
+ if (/^- /m.test(section))
370
462
  overrides[keys[index]] = section;
371
463
  });
372
- return { overrides, skipped: queue.skippedUnits() };
464
+ return { overrides };
373
465
  }
@@ -11,6 +11,10 @@ export type PullRequest = {
11
11
  additions: number;
12
12
  deletions: number;
13
13
  comments: string[];
14
+ /** Inline review comments (`pulls/{n}/comments`), as `path:line body`. These
15
+ * carry most of the substantive review feedback, and the reviewer never sees
16
+ * them otherwise. */
17
+ reviewComments: string[];
14
18
  reviews: string[];
15
19
  /** Set once reviews have been read. Missing means an older checkpoint
16
20
  * never stored the review state. */
@@ -44,6 +48,24 @@ export type Fact = {
44
48
  * repository-wide rule. Missing means `repository`, which
45
49
  * keeps facts written before this field existed. */
46
50
  origin?: "repository" | "pull-request";
51
+ /** Review findings only (`sectionKey === "review"`): the free-form area the
52
+ * finding belongs to, so the guide can group findings into passes without a
53
+ * fixed taxonomy. */
54
+ class?: string;
55
+ /** A repository-relative path or `path:line` the finding is about, when the
56
+ * review named one. Kept because it is the difference between a concrete
57
+ * rule and generic advice. */
58
+ location?: string;
59
+ /** Review findings only: why the finding matters here, in one or two
60
+ * sentences of the review's own reasoning (never a verbatim quote). */
61
+ impact?: string;
62
+ /** Review findings only: what to change or verify. */
63
+ action?: string;
64
+ /** Review findings only: the diff surface that should trigger this rule: a
65
+ * path, a glob, or a symbol. The guide turns these into the "when X changes,
66
+ * also do Y" obligations listed under a pass's exit check, so a reviewer that
67
+ * only sees a diff can still apply the rule. */
68
+ trigger?: string;
47
69
  };
48
70
  export type State = {
49
71
  version: 1;
@@ -1,5 +1,5 @@
1
1
  import { parseArgs } from "../cli/args.js";
2
- import { filterReviewConfigArgs, } from "../cli/review_args.js";
2
+ import { filterReviewConfigArgs, loadReviewSystemPromptFlags, reviewSystemPromptLimitFor, } from "../cli/review_args.js";
3
3
  import { buildLocalReviewJson, formatHumanLocalReview, humanFindingsFromResolved, resolvedFromFirstReview, reviewExitCodeFromResolved, } from "../cli/review_result.js";
4
4
  import { addAiMetrics, emptyAiMetrics, recordAiCost, runInitOrRemake, } from "../services/setup.js";
5
5
  import { aiFor } from "../services/review.js";
@@ -107,6 +107,9 @@ export async function runLocalReview(cli) {
107
107
  ...filterReviewConfigArgs(cli.rawArgs),
108
108
  ]);
109
109
  options.useCodegraph = cli.disableCodegraph ? false : true;
110
+ const promptFlags = await loadReviewSystemPromptFlags(cli, reviewSystemPromptLimitFor(repo));
111
+ options.reviewSystemPromptAdd = promptFlags.add;
112
+ options.reviewSystemPromptOverride = promptFlags.override;
110
113
  const guides = await loadGuides(repo);
111
114
  if (!guides.shortGuide && !guides.skill) {
112
115
  throw new ReviewCliError("not_initialized", `Review guides are missing for ${repo}.`, `co-maintainer init ${repo}`);
@@ -5,6 +5,7 @@ import { loadGuides } from "../review/guides.js";
5
5
  import { computeScope } from "./scope.js";
6
6
  import { prepareCodegraphTools } from "./codegraph_tools.js";
7
7
  import { REVIEW_COPY_RULE, severitySection } from "./review_copy.js";
8
+ import { reviewSystemPromptBlock } from "../review/system_prompt.js";
8
9
  import { needsSummary, READ_FULL_DIFF_TOOL, readFullDiff, summarizeDiff, } from "./diff_summary.js";
9
10
  import { numberPatch } from "./hunks.js";
10
11
  import { FINDINGS_JSON_INSTRUCTIONS, FINDINGS_JSON_SCHEMA, findingsMarkdownFromJson, } from "./findings_json.js";
@@ -370,7 +371,7 @@ ${diff}`;
370
371
  const matrix = clampImproveMatrix(options.improveMatrix);
371
372
  const request = {
372
373
  job: "review_pull_request",
373
- system: `${reviewSystemPrompt(diagrams)}\n\n${reviewGuidesBlock(guide, detailed, codebase)}`,
374
+ system: `${reviewSystemPrompt(diagrams)}\n\n${reviewGuidesBlock(guide, detailed, codebase)}${reviewSystemPromptBlock(options)}`,
374
375
  prompt,
375
376
  maxTokens: 24_000 * matrix,
376
377
  reasoningEffort: "high",
@@ -534,7 +535,7 @@ ${ownDiff}${unchangedListing}`;
534
535
  const matrix = clampImproveMatrix(options.improveMatrix);
535
536
  const request = {
536
537
  job: "review_local",
537
- system: `${reviewSystemPrompt(diagrams)}\n\n${reviewGuidesBlock(guide, detailed, codebase)}`,
538
+ system: `${reviewSystemPrompt(diagrams)}\n\n${reviewGuidesBlock(guide, detailed, codebase)}${reviewSystemPromptBlock(options)}`,
538
539
  prompt,
539
540
  maxTokens: 24_000 * matrix,
540
541
  reasoningEffort: "high",
@@ -1,5 +1,6 @@
1
1
  import { VERSION } from "../version.js";
2
- import { CliError, EXIT_USAGE, exitWith } from "../cli/error.js";
2
+ import { loadReviewSystemPromptFlags } from "../cli/review_args.js";
3
+ import { exitWith } from "../cli/error.js";
3
4
  import { formatHumanReview, humanFindingsFromJson, reviewExitCodeFromJsonFindings, } from "../cli/review_result.js";
4
5
  import { baseUrl, die, readApiError, remoteFetch, remoteFromEnv, } from "./http.js";
5
6
  import { readConfig, writeUserConfig } from "../config.js";
@@ -140,6 +141,10 @@ export async function runRemoteReview(cli) {
140
141
  .filter((name) => REMOTE_KNOWN_TOOL_NAMES.has(name))
141
142
  .map((name) => ({ name }));
142
143
  const requestId = crypto.randomUUID();
144
+ // The review runs on the server, so the server's per-repo cap decides. The
145
+ // client only reads the files and sends them, and the server rejects an
146
+ // over-cap value with a 400.
147
+ const promptFlags = await loadReviewSystemPromptFlags(cli, null);
143
148
  const submitBody = {
144
149
  schemaVersion: REMOTE_SCHEMA_VERSION,
145
150
  requestId,
@@ -157,6 +162,14 @@ export async function runRemoteReview(cli) {
157
162
  // Only present when this run turned BYOK on; `byokKey` is
158
163
  // known to be set here because of the earlier `byokEnabled` guard.
159
164
  ...(byokEnabled ? { byok: { key: byokKey } } : {}),
165
+ // The client's one-run instructions, when given. The server applies
166
+ // them on top of its own per-repo prompt.
167
+ ...(promptFlags.add !== undefined
168
+ ? { systemPromptAdd: promptFlags.add }
169
+ : {}),
170
+ ...(promptFlags.override !== undefined
171
+ ? { systemPromptOverride: promptFlags.override }
172
+ : {}),
160
173
  };
161
174
  const serialized = JSON.stringify(submitBody);
162
175
  if (serialized.length > hs.limits.maxBodyBytes) {
@@ -6,6 +6,9 @@ export declare const MIN_SERVER_SCHEMA = 1;
6
6
  export declare const REMOTE_CLI_UPGRADE_COMMAND = "npm install -g co-maintainer@latest";
7
7
  export declare const REMOTE_MAX_BODY_BYTES = 52428800;
8
8
  export declare const REMOTE_SYNC_INTERVAL_SECONDS = 3;
9
+ /** Absolute ceiling on a client's one-run review instructions, before the
10
+ * repository's own cap is applied on the server. Guards the body size. */
11
+ export declare const REMOTE_MAX_SYSTEM_PROMPT_CHARS = 200000;
9
12
  /** SHA-256 of sorted `fixtures/v<N>/*.json` (name + contents, `\r\n` normalized
10
13
  * to `\n`); bump with schema version. */
11
14
  export declare const REMOTE_FIXTURE_HASH: Record<number, string>;
@@ -6,6 +6,9 @@ export const MIN_SERVER_SCHEMA = 1;
6
6
  export const REMOTE_CLI_UPGRADE_COMMAND = "npm install -g co-maintainer@latest";
7
7
  export const REMOTE_MAX_BODY_BYTES = 52_428_800;
8
8
  export const REMOTE_SYNC_INTERVAL_SECONDS = 3;
9
+ /** Absolute ceiling on a client's one-run review instructions, before the
10
+ * repository's own cap is applied on the server. Guards the body size. */
11
+ export const REMOTE_MAX_SYSTEM_PROMPT_CHARS = 200_000;
9
12
  /** SHA-256 of sorted `fixtures/v<N>/*.json` (name + contents, `\r\n` normalized
10
13
  * to `\n`); bump with schema version. */
11
14
  export const REMOTE_FIXTURE_HASH = {
@@ -1,5 +1,5 @@
1
1
  import { rejectEscapingPath } from "../pr/codegraph_tool_args.js";
2
- import { MIN_CLIENT_SCHEMA, REMOTE_KNOWN_TOOL_NAMES, REMOTE_SCHEMA_VERSION, REMOTE_SYNC_STATUSES, } from "./schema.js";
2
+ import { MIN_CLIENT_SCHEMA, REMOTE_KNOWN_TOOL_NAMES, REMOTE_MAX_SYSTEM_PROMPT_CHARS, REMOTE_SCHEMA_VERSION, REMOTE_SYNC_STATUSES, } from "./schema.js";
3
3
  const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
4
4
  const REVISION_STATUSES = new Set([
5
5
  "added",
@@ -188,6 +188,17 @@ export function validateSubmitRequest(body) {
188
188
  const revisionErr = validateRevisionPayload(body.revision);
189
189
  if (revisionErr)
190
190
  return revisionErr;
191
+ for (const field of ["systemPromptAdd", "systemPromptOverride"]) {
192
+ const value = body[field];
193
+ if (value === undefined)
194
+ continue;
195
+ if (typeof value !== "string") {
196
+ return bad(field, "must be a string");
197
+ }
198
+ if (value.length > REMOTE_MAX_SYSTEM_PROMPT_CHARS) {
199
+ return bad(field, "too long");
200
+ }
201
+ }
191
202
  if (body.capabilities !== undefined) {
192
203
  if (!isRecord(body.capabilities)) {
193
204
  return bad("capabilities", "must be an object");
@@ -0,0 +1,19 @@
1
+ /** The per-repository custom review instructions and the cap on them. The
2
+ * block is appended to the built-in reviewer system prompt (role, diagram
3
+ * rules and guide) as a separate section, so the built-in instructions are
4
+ * always kept. */
5
+ import type { Options } from "../types.ts";
6
+ import type { RepoConfig } from "../config.ts";
7
+ /** Default cap on `reviewSystemPrompt`, in characters. */
8
+ export declare const DEFAULT_REVIEW_SYSTEM_PROMPT_MAX_CHARS = 8000;
9
+ /** The repository's cap, or `null` for no limit. Unset takes the default; a
10
+ * non-positive value means unlimited. */
11
+ export declare function reviewSystemPromptLimit(repoConfig: Pick<RepoConfig, "reviewSystemPromptMaxChars"> | undefined): number | null;
12
+ /** The problem with a custom prompt, or `null` when it is fine. Blank text is
13
+ * allowed and means "off". */
14
+ export declare function checkReviewSystemPrompt(text: string, limit: number | null): string | null;
15
+ /** The extra system-prompt section for a review, or `""` when none applies.
16
+ * A per-run override replaces the repository's own section, and a per-run add
17
+ * is appended after it. A blank per-run value counts as absent, so an empty
18
+ * override file keeps the repository's own section rather than dropping it. */
19
+ export declare function reviewSystemPromptBlock(options: Pick<Options, "reviewSystemPrompt" | "reviewSystemPromptAdd" | "reviewSystemPromptOverride">): string;
@@ -0,0 +1,34 @@
1
+ /** Default cap on `reviewSystemPrompt`, in characters. */
2
+ export const DEFAULT_REVIEW_SYSTEM_PROMPT_MAX_CHARS = 8000;
3
+ /** The repository's cap, or `null` for no limit. Unset takes the default; a
4
+ * non-positive value means unlimited. */
5
+ export function reviewSystemPromptLimit(repoConfig) {
6
+ const raw = repoConfig?.reviewSystemPromptMaxChars;
7
+ if (raw === undefined)
8
+ return DEFAULT_REVIEW_SYSTEM_PROMPT_MAX_CHARS;
9
+ if (!Number.isFinite(raw) || raw <= 0)
10
+ return null;
11
+ const floored = Math.floor(raw);
12
+ return floored > 0 ? floored : null;
13
+ }
14
+ /** The problem with a custom prompt, or `null` when it is fine. Blank text is
15
+ * allowed and means "off". */
16
+ export function checkReviewSystemPrompt(text, limit) {
17
+ if (limit !== null && text.length > limit) {
18
+ return `must be at most ${limit} characters (got ${text.length})`;
19
+ }
20
+ return null;
21
+ }
22
+ /** The extra system-prompt section for a review, or `""` when none applies.
23
+ * A per-run override replaces the repository's own section, and a per-run add
24
+ * is appended after it. A blank per-run value counts as absent, so an empty
25
+ * override file keeps the repository's own section rather than dropping it. */
26
+ export function reviewSystemPromptBlock(options) {
27
+ const override = options.reviewSystemPromptOverride?.trim();
28
+ const base = override ? override : options.reviewSystemPrompt?.trim();
29
+ const add = options.reviewSystemPromptAdd?.trim();
30
+ const parts = [base, add].filter((part) => Boolean(part));
31
+ if (parts.length === 0)
32
+ return "";
33
+ return `\n\nCUSTOM REVIEW INSTRUCTIONS:\n${parts.join("\n\n")}`;
34
+ }