co-maintainer 0.7.2 → 0.7.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 (59) hide show
  1. package/dist/package.json +1 -1
  2. package/dist/src/cli/command_json.d.ts +3 -1
  3. package/dist/src/cli/command_json.js +1 -0
  4. package/dist/src/cli/commands/review.js +2 -0
  5. package/dist/src/cli/commands/set.js +19 -2
  6. package/dist/src/cli/pr_carry.d.ts +2 -0
  7. package/dist/src/cli/pr_carry.js +2 -2
  8. package/dist/src/cli/review_carry.d.ts +3 -1
  9. package/dist/src/cli/review_carry.js +5 -3
  10. package/dist/src/cli/review_result.d.ts +10 -1
  11. package/dist/src/cli/review_result.js +14 -1
  12. package/dist/src/config.d.ts +9 -0
  13. package/dist/src/github/collect.d.ts +7 -1
  14. package/dist/src/github/collect.js +41 -16
  15. package/dist/src/knowledge/guide.d.ts +24 -1
  16. package/dist/src/knowledge/guide.js +39 -9
  17. package/dist/src/knowledge/guide_ids.d.ts +9 -0
  18. package/dist/src/knowledge/guide_ids.js +26 -7
  19. package/dist/src/knowledge/rule_changes.d.ts +18 -0
  20. package/dist/src/knowledge/rule_changes.js +41 -0
  21. package/dist/src/knowledge/rules.d.ts +11 -0
  22. package/dist/src/knowledge/rules.js +10 -1
  23. package/dist/src/knowledge/stable_ids.d.ts +34 -0
  24. package/dist/src/knowledge/stable_ids.js +124 -0
  25. package/dist/src/knowledge/synthesis.d.ts +13 -1
  26. package/dist/src/knowledge/synthesis.js +89 -21
  27. package/dist/src/knowledge/types.d.ts +16 -0
  28. package/dist/src/local/review_local.js +3 -2
  29. package/dist/src/pr/findings.d.ts +3 -0
  30. package/dist/src/pr/findings.js +21 -1
  31. package/dist/src/pr/findings_json.d.ts +1 -1
  32. package/dist/src/pr/findings_json.js +14 -1
  33. package/dist/src/pr/reviewer.d.ts +4 -0
  34. package/dist/src/pr/reviewer.js +2 -0
  35. package/dist/src/remote/client.js +1 -0
  36. package/dist/src/review/carry_over.d.ts +8 -0
  37. package/dist/src/review/carry_over.js +8 -0
  38. package/dist/src/review/references.d.ts +68 -0
  39. package/dist/src/review/references.js +176 -0
  40. package/dist/src/server/pages/pr.js +2 -0
  41. package/dist/src/server/pages/references.d.ts +2 -0
  42. package/dist/src/server/pages/references.js +55 -0
  43. package/dist/src/server/pages/repo.js +26 -0
  44. package/dist/src/services/dashboard.d.ts +2 -0
  45. package/dist/src/services/dashboard.js +2 -0
  46. package/dist/src/services/push_review.js +4 -1
  47. package/dist/src/services/remote_review.js +5 -2
  48. package/dist/src/services/review.js +35 -8
  49. package/dist/src/services/rules_build.d.ts +20 -1
  50. package/dist/src/services/rules_build.js +88 -6
  51. package/dist/src/services/setup.js +27 -2
  52. package/dist/src/store/findings.d.ts +2 -0
  53. package/dist/src/store/findings.js +3 -3
  54. package/dist/src/store/migrations.js +17 -0
  55. package/dist/src/store/rows.d.ts +2 -0
  56. package/dist/src/store/rule_events.d.ts +15 -0
  57. package/dist/src/store/rule_events.js +20 -0
  58. package/dist/src/types.d.ts +4 -0
  59. package/package.json +1 -1
@@ -32,6 +32,18 @@ function takeSourceBracket(line) {
32
32
  function setKey(numbers) {
33
33
  return numbers.join(",");
34
34
  }
35
+ /** `(overturns R4, R7)` right before the source bracket. */
36
+ const OVERTURNS = /\s*\(overturns\s+(R[1-9]\d*(?:\s*,\s*R[1-9]\d*)*)\)\s*$/;
37
+ /** The line without its overturns note, and the ids it named. */
38
+ export function takeOverturns(line) {
39
+ const match = OVERTURNS.exec(line);
40
+ if (!match)
41
+ return { line, ids: [] };
42
+ return {
43
+ line: line.slice(0, match.index),
44
+ ids: [...new Set(match[1].split(",").map((id) => id.trim()))],
45
+ };
46
+ }
35
47
  function ruleText(line) {
36
48
  return line.replace(/^- /, "").replaceAll("`", "").trim();
37
49
  }
@@ -54,7 +66,8 @@ function rewrite(text, file, findingCount, idFor) {
54
66
  if (valid.length === 0)
55
67
  return taken.line;
56
68
  withIds++;
57
- return `${taken.line} [${idFor(valid, taken.line)}]`;
69
+ const note = takeOverturns(taken.line);
70
+ return `${note.line} [${idFor(valid, note.line, note.ids)}]`;
58
71
  });
59
72
  return { text: lines.join("\n"), count: { file, rules, withIds } };
60
73
  }
@@ -65,22 +78,28 @@ function rewrite(text, file, findingCount, idFor) {
65
78
  export function assignGuideIds(guide, detailed, findingCount) {
66
79
  const rules = [];
67
80
  const bySet = new Map();
68
- const add = (file, numbers, line) => {
81
+ const add = (file, numbers, line, overturns = []) => {
69
82
  const id = `R${rules.length + 1}`;
70
- rules.push({ id, file, text: ruleText(line), findings: numbers });
83
+ rules.push({
84
+ id,
85
+ file,
86
+ text: ruleText(line),
87
+ findings: numbers,
88
+ ...(overturns.length ? { overturns } : {}),
89
+ });
71
90
  return id;
72
91
  };
73
92
  if (detailed === undefined) {
74
- const single = rewrite(guide, GUIDE_FILE, findingCount, (numbers, line) => add(GUIDE_FILE, numbers, line));
93
+ const single = rewrite(guide, GUIDE_FILE, findingCount, (numbers, line, overturns) => add(GUIDE_FILE, numbers, line, overturns));
75
94
  return { guide: single.text, rules, counts: [single.count] };
76
95
  }
77
- const full = rewrite(detailed, DETAILED_GUIDE_FILE, findingCount, (numbers, line) => {
78
- const id = add(DETAILED_GUIDE_FILE, numbers, line);
96
+ const full = rewrite(detailed, DETAILED_GUIDE_FILE, findingCount, (numbers, line, overturns) => {
97
+ const id = add(DETAILED_GUIDE_FILE, numbers, line, overturns);
79
98
  if (!bySet.has(setKey(numbers)))
80
99
  bySet.set(setKey(numbers), id);
81
100
  return id;
82
101
  });
83
- const short = rewrite(guide, GUIDE_FILE, findingCount, (numbers, line) => bySet.get(setKey(numbers)) ?? add(GUIDE_FILE, numbers, line));
102
+ const short = rewrite(guide, GUIDE_FILE, findingCount, (numbers, line, overturns) => bySet.get(setKey(numbers)) ?? add(GUIDE_FILE, numbers, line, overturns));
84
103
  return {
85
104
  guide: short.text,
86
105
  detailed: full.text,
@@ -40,3 +40,21 @@ export declare function compareRules(previous: Record<string, RuleEntry> | undef
40
40
  /** `2 rules added (#402, #407) · 1 rewritten (R12, #340 joined) · 1 dropped
41
41
  * (#101 left the window)`, or `no rule changed`. */
42
42
  export declare function ruleChangeLine(changes: RuleChanges): string;
43
+ export type Contradiction = {
44
+ /** The old rule. */
45
+ id: string;
46
+ /** The new rule that goes against it. */
47
+ by: string;
48
+ /** The new rule's pull requests, `#340`. */
49
+ sources: string[];
50
+ /** The newest merge date of the new rule, `YYYY-MM-DD`. */
51
+ newest: string;
52
+ /** False when the old id is still in this build. */
53
+ dropped: boolean;
54
+ };
55
+ /** The old rules the guide AI said a new rule goes against, kept only when
56
+ * the old rule existed and the new rule's newest pull request was merged
57
+ * after the old rule's newest one. Without both dates nothing is claimed. */
58
+ export declare function contradictions(previous: Record<string, RuleEntry> | undefined, next: Record<string, RuleEntry>, overturns: Map<string, string[]>): Contradiction[];
59
+ /** `R4 dropped, R9 goes against it (#340, 2026-03)`. */
60
+ export declare function contradictionLine(item: Contradiction): string;
@@ -96,3 +96,44 @@ export function ruleChangeLine(changes) {
96
96
  }
97
97
  return parts.length > 0 ? parts.join(" · ") : "no rule changed";
98
98
  }
99
+ function newestDate(entry) {
100
+ const dates = entry.sources.flatMap((source) => "pr" in source && source.mergedAt ? [source.mergedAt] : []);
101
+ return dates.length ? dates.sort().at(-1) : undefined;
102
+ }
103
+ /** The old rules the guide AI said a new rule goes against, kept only when
104
+ * the old rule existed and the new rule's newest pull request was merged
105
+ * after the old rule's newest one. Without both dates nothing is claimed. */
106
+ export function contradictions(previous, next, overturns) {
107
+ const found = [];
108
+ for (const [by, ids] of overturns) {
109
+ const entry = next[by];
110
+ if (!entry)
111
+ continue;
112
+ const newest = newestDate(entry);
113
+ if (!newest)
114
+ continue;
115
+ for (const id of ids) {
116
+ const old = previous?.[id];
117
+ if (!old || id === by)
118
+ continue;
119
+ const oldNewest = newestDate(old);
120
+ if (!oldNewest || newest <= oldNewest)
121
+ continue;
122
+ found.push({
123
+ id,
124
+ by,
125
+ sources: labels(entry),
126
+ newest,
127
+ dropped: !(id in next),
128
+ });
129
+ }
130
+ }
131
+ return found;
132
+ }
133
+ /** `R4 dropped, R9 goes against it (#340, 2026-03)`. */
134
+ export function contradictionLine(item) {
135
+ const evidence = `${listed(item.sources, 3)}, ${item.newest.slice(0, 7)}`;
136
+ return item.dropped
137
+ ? `${item.id} dropped, ${item.by} goes against it (${evidence})`
138
+ : `${item.by} goes against ${item.id} (${evidence})`;
139
+ }
@@ -16,6 +16,10 @@ export declare const DETAILED_GUIDE_FILE = "PR_REVIEW_DETAILED_GUIDE.md";
16
16
  export type RuleSource = {
17
17
  pr: number;
18
18
  mergedAt?: string;
19
+ /** The review comment the rule came from. Missing when the pull
20
+ * request was read before links were kept, or the rule came from its
21
+ * body or diff. */
22
+ url?: string;
19
23
  } | {
20
24
  path: string;
21
25
  line: number;
@@ -35,6 +39,13 @@ export type RulesFile = {
35
39
  schemaVersion: 1;
36
40
  builtAt: string;
37
41
  rules: Record<string, RuleEntry>;
42
+ /** The highest number ever given per kind, so a dropped id is never given
43
+ * to another rule. Missing in files written before ids were kept stable:
44
+ * the highest id in `rules` stands in. */
45
+ lastIds?: {
46
+ R: number;
47
+ I: number;
48
+ };
38
49
  };
39
50
  /** Ids are `R` for guide rules and `I` for instruction rules, then a number.
40
51
  * `C` is kept for built-in checks. */
@@ -18,7 +18,8 @@ function isSource(value) {
18
18
  return false;
19
19
  const record = value;
20
20
  if (typeof record.pr === "number") {
21
- return record.mergedAt === undefined || typeof record.mergedAt === "string";
21
+ return ((record.mergedAt === undefined || typeof record.mergedAt === "string") &&
22
+ (record.url === undefined || typeof record.url === "string"));
22
23
  }
23
24
  return typeof record.path === "string" && typeof record.line === "number";
24
25
  }
@@ -58,10 +59,18 @@ export function parseRules(text) {
58
59
  sources,
59
60
  };
60
61
  }
62
+ const last = record.lastIds;
63
+ const lastIds = last &&
64
+ typeof last === "object" &&
65
+ Number.isInteger(last.R) &&
66
+ Number.isInteger(last.I)
67
+ ? { R: Number(last.R), I: Number(last.I) }
68
+ : undefined;
61
69
  return {
62
70
  schemaVersion: 1,
63
71
  builtAt: typeof record.builtAt === "string" ? record.builtAt : "",
64
72
  rules,
73
+ ...(lastIds ? { lastIds } : {}),
65
74
  };
66
75
  }
67
76
  function idNumber(id) {
@@ -0,0 +1,34 @@
1
+ /** Rule ids that stay the same across builds.
2
+ *
3
+ * A build numbers its rules from 1 (`R1`, `I1`, ...). A review that cited
4
+ * `R4` must still point at the same rule after the next `sync`, so the fresh
5
+ * numbers are mapped onto the last build's ids before anything is written:
6
+ * a rule that shares a source with an old rule keeps that rule's id (it is the
7
+ * same rule, maybe reworded), a rule with no match gets the next number ever
8
+ * given, and a dropped id is never given again. */
9
+ import { type RuleEntry, type RuleSource } from "./rules.ts";
10
+ export type FreshRule = {
11
+ id: string;
12
+ text: string;
13
+ sources: RuleSource[];
14
+ /** Old ids this rule may not take, such as the rule it overturns. */
15
+ avoid?: string[];
16
+ };
17
+ /** Maps each fresh id to its stable id, and returns the new highest number.
18
+ * A fresh rule may keep an old id when it shares a source with that rule, or
19
+ * else has the same text. The ids are matched as a whole, not first come
20
+ * first served: a rule that could keep two ids gives way to a later rule that
21
+ * can keep only one of them, so as many ids as possible stay the same.
22
+ *
23
+ * Among its options a rule tries the best first: each shared pull request or
24
+ * file line counts 1, a shared review comment link 1 more, and text
25
+ * similarity adds less than one source. So two rules that rest on the same
26
+ * pull request keep their own ids, by their comment links when both builds
27
+ * kept them, or else by their wording. */
28
+ export declare function stableIds(kind: "R" | "I", fresh: FreshRule[], previous: Record<string, RuleEntry> | undefined, lastId: number | undefined): {
29
+ ids: Map<string, string>;
30
+ lastId: number;
31
+ };
32
+ /** Rewrites the `[R1]` / `[I1]` id at the end of each line in one pass, so a
33
+ * rename such as R1 to R2 and R2 to R5 never collides. */
34
+ export declare function renameIdsInMarkdown(markdown: string, ids: Map<string, string>): string;
@@ -0,0 +1,124 @@
1
+ /** Rule ids that stay the same across builds.
2
+ *
3
+ * A build numbers its rules from 1 (`R1`, `I1`, ...). A review that cited
4
+ * `R4` must still point at the same rule after the next `sync`, so the fresh
5
+ * numbers are mapped onto the last build's ids before anything is written:
6
+ * a rule that shares a source with an old rule keeps that rule's id (it is the
7
+ * same rule, maybe reworded), a rule with no match gets the next number ever
8
+ * given, and a dropped id is never given again. */
9
+ import { sourceLabel } from "./rules.js";
10
+ /** The highest id number of one kind in `rules`. */
11
+ function highest(rules, kind) {
12
+ let max = 0;
13
+ for (const id of Object.keys(rules)) {
14
+ if (id.startsWith(kind))
15
+ max = Math.max(max, Number(id.slice(1)) || 0);
16
+ }
17
+ return max;
18
+ }
19
+ /** What a source can match on: its pull request or file line, and for a
20
+ * guide rule also the review comment it came from. Two rules on the same pull
21
+ * request share `#4` but not their comment links. */
22
+ function matchKeys(source) {
23
+ const url = "pr" in source ? source.url : undefined;
24
+ return url ? [sourceLabel(source), url] : [sourceLabel(source)];
25
+ }
26
+ function words(text) {
27
+ return new Set(text
28
+ .toLowerCase()
29
+ .split(/[^\p{L}\p{N}]+/u)
30
+ .filter((word) => word.length > 2));
31
+ }
32
+ /** Shared words over all words, from 0 to 1. */
33
+ function similarity(a, b) {
34
+ if (a.size === 0 && b.size === 0)
35
+ return 1;
36
+ let shared = 0;
37
+ for (const word of a)
38
+ if (b.has(word))
39
+ shared++;
40
+ return shared / (a.size + b.size - shared);
41
+ }
42
+ /** Maps each fresh id to its stable id, and returns the new highest number.
43
+ * A fresh rule may keep an old id when it shares a source with that rule, or
44
+ * else has the same text. The ids are matched as a whole, not first come
45
+ * first served: a rule that could keep two ids gives way to a later rule that
46
+ * can keep only one of them, so as many ids as possible stay the same.
47
+ *
48
+ * Among its options a rule tries the best first: each shared pull request or
49
+ * file line counts 1, a shared review comment link 1 more, and text
50
+ * similarity adds less than one source. So two rules that rest on the same
51
+ * pull request keep their own ids, by their comment links when both builds
52
+ * kept them, or else by their wording. */
53
+ export function stableIds(kind, fresh, previous, lastId) {
54
+ const old = Object.entries(previous ?? {})
55
+ .filter(([id]) => id.startsWith(kind))
56
+ .map(([id, entry]) => ({
57
+ id,
58
+ text: entry.text,
59
+ words: words(entry.text),
60
+ keys: new Set(entry.sources.flatMap(matchKeys)),
61
+ }));
62
+ const rules = fresh.filter((rule, index) => fresh.findIndex((item) => item.id === rule.id) === index);
63
+ // Each rule's old ids it may keep, best first.
64
+ const options = rules.map((rule) => {
65
+ const keys = [...new Set(rule.sources.flatMap(matchKeys))];
66
+ const own = words(rule.text);
67
+ return old
68
+ .flatMap((item, order) => {
69
+ if (rule.avoid?.includes(item.id))
70
+ return [];
71
+ const shared = keys.filter((key) => item.keys.has(key)).length;
72
+ // Same text with no shared source still counts, below any shared
73
+ // source: an instruction line that moved down a file is the same rule.
74
+ const score = shared > 0
75
+ ? shared + 0.5 * similarity(own, item.words)
76
+ : item.text === rule.text
77
+ ? 0.5
78
+ : 0;
79
+ return score > 0 ? [{ id: item.id, score, order }] : [];
80
+ })
81
+ .sort((a, b) => b.score - a.score || a.order - b.order)
82
+ .map((option) => option.id);
83
+ });
84
+ // Augmenting paths: a rule takes a free id, or moves the rule holding one
85
+ // of its options to another id that rule may keep.
86
+ const holder = new Map();
87
+ const kept = new Map();
88
+ const place = (index, seen) => {
89
+ for (const id of options[index]) {
90
+ if (seen.has(id))
91
+ continue;
92
+ seen.add(id);
93
+ const current = holder.get(id);
94
+ if (current === undefined || place(current, seen)) {
95
+ holder.set(id, index);
96
+ kept.set(index, id);
97
+ return true;
98
+ }
99
+ }
100
+ return false;
101
+ };
102
+ for (let index = 0; index < rules.length; index++)
103
+ place(index, new Set());
104
+ let next = Math.max(lastId ?? 0, highest(previous ?? {}, kind));
105
+ const ids = new Map();
106
+ for (const [index, rule] of rules.entries()) {
107
+ const id = kept.get(index);
108
+ if (id)
109
+ ids.set(rule.id, id);
110
+ else {
111
+ next++;
112
+ ids.set(rule.id, `${kind}${next}`);
113
+ }
114
+ }
115
+ return { ids, lastId: next };
116
+ }
117
+ /** Rewrites the `[R1]` / `[I1]` id at the end of each line in one pass, so a
118
+ * rename such as R1 to R2 and R2 to R5 never collides. */
119
+ export function renameIdsInMarkdown(markdown, ids) {
120
+ return markdown.replace(/\[([RI][1-9]\d*)\](?=[ \t]*$)/gm, (whole, id) => {
121
+ const renamed = ids.get(id);
122
+ return renamed ? `[${renamed}]` : whole;
123
+ });
124
+ }
@@ -1,6 +1,18 @@
1
1
  import type { AiProvider, AiResponse, Options } from "../types.ts";
2
- import type { Fact, Source } from "./types.ts";
2
+ import type { Fact, PullRequest, Source } from "./types.ts";
3
3
  type UsageSink = (job: string, response: AiResponse) => Promise<void>;
4
+ /** Whether the pull request was read with comment links. A row cached before
5
+ * links were kept has none, and keeps the old extract prompt so its cached
6
+ * answer is still used. */
7
+ export declare function hasCommentLinks(pr: PullRequest): boolean;
8
+ /** The comment ids of a linked pull request (`c1` issue comment, `r1` inline
9
+ * review comment, `v1` review) and the link behind each. */
10
+ export declare function commentIds(pr: PullRequest): Map<string, string>;
11
+ /** The extract prompt for one pull request. A pull request read before
12
+ * comment links were kept gets the exact old text, so its cached answer still
13
+ * hits. A linked one numbers its comments and asks which ones a finding rests
14
+ * on. */
15
+ export declare function extractPrompt(pr: PullRequest): string;
4
16
  export type SynthesisResult = Record<string, string>;
5
17
  export declare function extractAiFacts(provider: AiProvider, repo: string, source: Source, options: Options, usage?: UsageSink): Promise<Fact[]>;
6
18
  export declare function enrichFacts(provider: AiProvider, repo: string, base: Fact[], source: Source, options: Options, usage?: UsageSink): Promise<Fact[]>;
@@ -97,7 +97,7 @@ function parseJson(text) {
97
97
  }
98
98
  return [];
99
99
  }
100
- function factsFromResponse(text, evidence, defaultScope, origin) {
100
+ function factsFromResponse(text, evidence, defaultScope, origin, pr, ids) {
101
101
  const parsed = parseJson(text);
102
102
  if (!Array.isArray(parsed))
103
103
  return [];
@@ -128,6 +128,7 @@ function factsFromResponse(text, evidence, defaultScope, origin) {
128
128
  const trigger = String(value.trigger ?? "").trim();
129
129
  if (isReview && (!impact || !action))
130
130
  return [];
131
+ const links = isReview ? linksFor(value.sources, pr, ids) : [];
131
132
  return [
132
133
  {
133
134
  id: `${sectionKey}:${slug(claim)}`,
@@ -146,6 +147,7 @@ function factsFromResponse(text, evidence, defaultScope, origin) {
146
147
  ...(trigger ? { trigger } : {}),
147
148
  impact,
148
149
  action,
150
+ ...(links.length ? { links } : {}),
149
151
  }
150
152
  : {}),
151
153
  },
@@ -187,19 +189,88 @@ function hasUnsupportedPath(claim, source) {
187
189
  ![...paths].some((path) => wildcard ? wildcard.test(path) : path.startsWith(`${normalized}/`)));
188
190
  });
189
191
  }
190
- function pullRequestUnit(pr) {
192
+ /** Whether the pull request was read with comment links. A row cached before
193
+ * links were kept has none, and keeps the old extract prompt so its cached
194
+ * answer is still used. */
195
+ export function hasCommentLinks(pr) {
196
+ return (pr.commentUrls !== undefined ||
197
+ pr.reviewCommentUrls !== undefined ||
198
+ pr.reviewUrls !== undefined);
199
+ }
200
+ /** The comment ids of a linked pull request (`c1` issue comment, `r1` inline
201
+ * review comment, `v1` review) and the link behind each. */
202
+ export function commentIds(pr) {
203
+ const ids = new Map();
204
+ const add = (prefix, urls, count) => {
205
+ for (let index = 0; index < count; index++) {
206
+ const url = urls?.[index] ?? "";
207
+ if (url)
208
+ ids.set(`${prefix}${index + 1}`, url);
209
+ }
210
+ };
211
+ add("c", pr.commentUrls, pr.comments.length);
212
+ add("r", pr.reviewCommentUrls, pr.reviewComments.length);
213
+ add("v", pr.reviewUrls, pr.reviews.length);
214
+ return ids;
215
+ }
216
+ function pullRequestUnit(pr, numbered = false) {
217
+ const texts = (prefix, values) => values.map((value, index) => {
218
+ const text = promptText(value, 2_000);
219
+ return numbered ? `[${prefix}${index + 1}] ${text}` : text;
220
+ });
191
221
  return JSON.stringify({
192
222
  number: pr.number,
193
223
  title: pr.title,
194
224
  body: promptText(pr.body),
195
225
  labels: pr.labels,
196
- comments: pr.comments.map((comment) => promptText(comment, 2_000)),
197
- reviewComments: pr.reviewComments.map((comment) => promptText(comment, 2_000)),
198
- reviews: pr.reviews.map((review) => promptText(review, 2_000)),
226
+ comments: texts("c", pr.comments),
227
+ reviewComments: texts("r", pr.reviewComments),
228
+ reviews: texts("v", pr.reviews),
199
229
  changedFiles: pr.changedFiles,
200
230
  diff: promptText(pr.diff, 8_000),
201
231
  });
202
232
  }
233
+ /** The extract prompt for one pull request. A pull request read before
234
+ * comment links were kept gets the exact old text, so its cached answer still
235
+ * hits. A linked one numbers its comments and asks which ones a finding rests
236
+ * on. */
237
+ export function extractPrompt(pr) {
238
+ const numbered = hasCommentLinks(pr);
239
+ const sourcesField = numbered
240
+ ? ',"sources":["the ids of the comments or reviews the finding comes from, such as r2 or v1, empty when it comes from the body or the diff"]'
241
+ : "";
242
+ const sourcesRule = numbered
243
+ ? "\n- Every comment and review starts with its id in square brackets. List in sources only ids that appear in this pull request."
244
+ : "";
245
+ return `Analyze this pull request's reviews, comments, code and diff, and return only a JSON array of review findings.
246
+ Each item must have exactly:
247
+ {"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"${sourcesField}}
248
+ Rules:
249
+ - Include only substantive findings: a reviewer identifies something to fix, change, verify or decide.
250
+ - Never write an approval, a merge, "LGTM", thanks, a reviewer name, a pull-request number, a commit id, or quoted comment text.
251
+ - 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".
252
+ - 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.
253
+ - impact and action are mandatory and concrete. Paraphrase the reviewer's reasoning for impact. Never quote it.
254
+ - 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.
255
+ - location is a repository path when the review names one, otherwise leave it empty.${sourcesRule}
256
+ - Return every distinct finding the reviews support, not a summary. Do not explain the answer.
257
+
258
+ PULL REQUEST:
259
+ ${pullRequestUnit(pr, numbered)}`;
260
+ }
261
+ /** The links a finding's `sources` name. An id the pull request does not have
262
+ * is dropped, so a made-up id never becomes a link. */
263
+ function linksFor(value, pr, ids) {
264
+ if (pr === undefined || !ids || !Array.isArray(value))
265
+ return [];
266
+ const urls = new Set();
267
+ for (const item of value) {
268
+ const url = ids.get(String(item).trim().toLowerCase());
269
+ if (url)
270
+ urls.add(url);
271
+ }
272
+ return [...urls].map((url) => ({ pr, url }));
273
+ }
203
274
  function queueFor(provider, repo, ai, model, concurrency, validate) {
204
275
  return new AiBatch(provider, repo, Math.max(1, concurrency), `${ai}:v3:${model}`, validate);
205
276
  }
@@ -291,23 +362,15 @@ export async function extractAiFacts(provider, repo, source, options, usage) {
291
362
  const requests = [];
292
363
  const evidence = [];
293
364
  const scopes = [];
365
+ // Per request: the comment ids of a linked pull request and its number,
366
+ // `undefined` for the repository files request and unlinked pull requests.
367
+ const linkIds = [];
368
+ const prNumbers = [];
294
369
  const prs = options.includePullRequests ? source.pullRequests : [];
295
370
  for (const pr of prs) {
296
- requests.push(extractRequest(`Analyze this pull request's reviews, comments, code and diff, and return only a JSON array of review findings.
297
- Each item must have exactly:
298
- {"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"}
299
- Rules:
300
- - Include only substantive findings: a reviewer identifies something to fix, change, verify or decide.
301
- - Never write an approval, a merge, "LGTM", thanks, a reviewer name, a pull-request number, a commit id, or quoted comment text.
302
- - 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".
303
- - 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.
304
- - impact and action are mandatory and concrete. Paraphrase the reviewer's reasoning for impact. Never quote it.
305
- - 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.
306
- - location is a repository path when the review names one, otherwise leave it empty.
307
- - Return every distinct finding the reviews support, not a summary. Do not explain the answer.
308
-
309
- PULL REQUEST:
310
- ${pullRequestUnit(pr)}`, 2_400));
371
+ requests.push(extractRequest(extractPrompt(pr), 2_400));
372
+ linkIds.push(hasCommentLinks(pr) ? commentIds(pr) : undefined);
373
+ prNumbers.push(pr.number);
311
374
  evidence.push(`PR #${pr.number}`);
312
375
  scopes.push("historical-example");
313
376
  }
@@ -333,6 +396,8 @@ Return at most 10 items. Keep each claim under 180 characters. Do not explain th
333
396
  FILES:
334
397
  ${files}`, 2_200));
335
398
  evidence.push("repository files");
399
+ linkIds.push(undefined);
400
+ prNumbers.push(undefined);
336
401
  scopes.push("current");
337
402
  }
338
403
  }
@@ -349,7 +414,7 @@ ${files}`, 2_200));
349
414
  const response = responses[index];
350
415
  if (!response)
351
416
  continue;
352
- facts.push(...factsFromResponse(response.text, evidence[index], scopes[index] ?? "historical-example", evidence[index] === "repository files" ? "repository" : "pull-request").filter((item) => {
417
+ facts.push(...factsFromResponse(response.text, evidence[index], scopes[index] ?? "historical-example", evidence[index] === "repository files" ? "repository" : "pull-request", prNumbers[index], linkIds[index]).filter((item) => {
353
418
  if (hasUnsupportedIdentifier(item.claim, source) ||
354
419
  hasUnsupportedPath(item.claim, source)) {
355
420
  return false;
@@ -388,6 +453,9 @@ function mergeFacts(base, extra) {
388
453
  existing.evidence = [
389
454
  ...new Set([...existing.evidence, ...item.evidence]),
390
455
  ];
456
+ const links = [...(existing.links ?? []), ...(item.links ?? [])].filter((link, index, all) => all.findIndex((other) => other.url === link.url) === index);
457
+ if (links.length)
458
+ existing.links = links;
391
459
  }
392
460
  }
393
461
  return [...merged.values()];
@@ -19,6 +19,13 @@ export type PullRequest = {
19
19
  * them otherwise. */
20
20
  reviewComments: string[];
21
21
  reviews: string[];
22
+ /** The GitHub link of each entry in `comments`, `reviewComments` and
23
+ * `reviews`, at the same index. Missing on rows cached before links were
24
+ * kept, and an entry is empty when GitHub gave no link. Never sent to a
25
+ * model: a fact names the numbered comment and code looks the link up. */
26
+ commentUrls?: string[];
27
+ reviewCommentUrls?: string[];
28
+ reviewUrls?: string[];
22
29
  /** Set once reviews have been read. Missing means an older checkpoint
23
30
  * never stored the review state. */
24
31
  changesRequested?: boolean;
@@ -72,6 +79,15 @@ export type Fact = {
72
79
  * also do Y" obligations listed under a pass's exit check, so a reviewer that
73
80
  * only sees a diff can still apply the rule. */
74
81
  trigger?: string;
82
+ /** Review findings only: the GitHub link of each comment or review the
83
+ * finding came from, with its pull request. The model names a numbered
84
+ * comment, code turns it into this link. Missing when the finding came from
85
+ * the body or the diff, or from a pull request cached before links were
86
+ * kept. */
87
+ links?: {
88
+ pr: number;
89
+ url: string;
90
+ }[];
75
91
  };
76
92
  export type State = {
77
93
  version: 1;
@@ -1,4 +1,5 @@
1
1
  import { parseArgs } from "../cli/args.js";
2
+ import { readConfig } from "../config.js";
2
3
  import { filterReviewConfigArgs, loadReviewSystemPromptFlags, reviewSystemPromptLimitFor, } from "../cli/review_args.js";
3
4
  import { buildLocalReviewJson, formatHumanLocalReview, humanFindingsFromResolved, reviewExitCodeFromResolved, } from "../cli/review_result.js";
4
5
  import { addAiMetrics, emptyAiMetrics, recordAiCost, runInitOrRemake, } from "../services/setup.js";
@@ -245,7 +246,7 @@ export async function runLocalReview(cli) {
245
246
  return;
246
247
  const codegraphState = codegraphPrep.state;
247
248
  warnings.push(...response.warnings);
248
- const { resolved: allResolved, visiblePaths } = finishCarryRun(carryRun, revision, response);
249
+ const { resolved: allResolved, visiblePaths } = finishCarryRun(carryRun, revision, response, options.repo);
249
250
  const findingsToStore = storedFindings(allResolved);
250
251
  const afterBuilt = await buildLocalRevision(root, baseSha, base.label, runCommand);
251
252
  const revisionHashAfter = await revisionHash(afterBuilt.revision);
@@ -315,7 +316,7 @@ export async function runLocalReview(cli) {
315
316
  }
316
317
  else {
317
318
  console.log("\n" +
318
- formatHumanLocalReview(header, revision, response.guideBuiltAt, codegraphState, allResolved, warnings, options.reviewBlocking, response.coverage, extensions, Boolean(intentLoad.intent)) +
319
+ formatHumanLocalReview(header, revision, response.guideBuiltAt, codegraphState, allResolved, warnings, options.reviewBlocking, response.coverage, extensions, Boolean(intentLoad.intent), readConfig().repos?.[options.repo]?.reviewReferences === true) +
319
320
  "\n");
320
321
  printRunSummary(run);
321
322
  }
@@ -10,5 +10,8 @@ export type ParsedFinding = Span & {
10
10
  blocking?: boolean;
11
11
  symbol?: string;
12
12
  summary?: string;
13
+ /** The ids from the finding's `References:` line, as the model wrote them.
14
+ * Missing when the line is absent. */
15
+ references?: string[];
13
16
  };
14
17
  export declare function parseFindings(markdown: string): ParsedFinding[];
@@ -22,8 +22,24 @@ function location(block) {
22
22
  to: found.groups.to ? Number(found.groups.to) : from,
23
23
  };
24
24
  }
25
+ /** The `References:` line, only right under the Location line where
26
+ * `findingMarkdown` writes it, so a body sentence starting with the same word
27
+ * is never taken. */
28
+ const REFERENCES_LINE = /^(\s*(?:Location|File)\s*:[^\n]*)\n\s*References\s*:\s*([^\n]+?)\s*$/im;
29
+ function references(block) {
30
+ const match = REFERENCES_LINE.exec(block);
31
+ if (!match)
32
+ return undefined;
33
+ return match[2]
34
+ .split(",")
35
+ .map((id) => id.trim())
36
+ .filter(Boolean);
37
+ }
25
38
  function bodyWithoutLocation(block) {
26
- return block.replace(/^\s*(?:Location|File)\s*:\s*`?.+?`?\s*$/im, "").trim();
39
+ return block
40
+ .replace(REFERENCES_LINE, "$1")
41
+ .replace(/^\s*(?:Location|File)\s*:\s*`?.+?`?\s*$/im, "")
42
+ .trim();
27
43
  }
28
44
  function newFinding(header, block) {
29
45
  const meta = NEW_HEADING.exec(header);
@@ -51,6 +67,10 @@ function newFinding(header, block) {
51
67
  blocking: impact === "blocking",
52
68
  symbol: symbol || undefined,
53
69
  summary,
70
+ ...(() => {
71
+ const ids = references(block);
72
+ return ids ? { references: ids } : {};
73
+ })(),
54
74
  };
55
75
  }
56
76
  export function parseFindings(markdown) {