co-maintainer 0.7.0-beta.4 → 0.7.1-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.
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "co-maintainer",
3
- "version": "0.7.0-beta.4",
3
+ "version": "0.7.1-beta.1",
4
4
  "description": "An imitator of yours, A PR review tool like co-maintainer.",
5
5
  "keywords": [
6
6
  "ai",
@@ -60,9 +60,10 @@ export type SetupJsonInput = {
60
60
  overCap: number;
61
61
  };
62
62
  };
63
- /** The full change lists behind the `[instructions]` line, or `null` when
64
- * there was no earlier `RULES.json`. */
63
+ /** The full change lists behind the `[guide]` and `[instructions]` lines,
64
+ * or `null` when there was no earlier `RULES.json`. */
65
65
  ruleChanges?: {
66
+ guide: RuleChanges;
66
67
  instructions: RuleChanges;
67
68
  } | null;
68
69
  summary: RunSummary;
@@ -678,7 +678,7 @@ export const COMMANDS = [
678
678
  },
679
679
  {
680
680
  name: "sources",
681
- description: "List every instruction rule by id, with the instruction file lines it came from.",
681
+ description: "List every guide and instruction rule by id, with the pull requests or instruction file lines it came from.",
682
682
  },
683
683
  {
684
684
  name: "json",
@@ -1,6 +1,9 @@
1
1
  /** `view --sources`: every rule id with where it came from.
2
2
  *
3
3
  * ```
4
+ * PR_REVIEW_GUIDE.md
5
+ * R12 Money formatting goes through formatMoney() · rounding differs per currency
6
+ * #212, #340 · newest 2026-03
4
7
  * INSTRUCTIONS.md
5
8
  * I1 Format amounts with formatMoney(), never with number methods
6
9
  * AGENTS.md:31 · packages/billing/AGENTS.md:8
@@ -1,18 +1,35 @@
1
1
  /** `view --sources`: every rule id with where it came from.
2
2
  *
3
3
  * ```
4
+ * PR_REVIEW_GUIDE.md
5
+ * R12 Money formatting goes through formatMoney() · rounding differs per currency
6
+ * #212, #340 · newest 2026-03
4
7
  * INSTRUCTIONS.md
5
8
  * I1 Format amounts with formatMoney(), never with number methods
6
9
  * AGENTS.md:31 · packages/billing/AGENTS.md:8
7
10
  * ```
8
11
  */
9
- import { INSTRUCTIONS_FILE, sortedRuleIds, sourceLabel, } from "../../knowledge/rules.js";
10
- const FILE_ORDER = [INSTRUCTIONS_FILE];
11
- /** The second line under a rule: its instruction file lines. */
12
+ import { DETAILED_GUIDE_FILE, GUIDE_FILE, INSTRUCTIONS_FILE, sortedRuleIds, sourceLabel, } from "../../knowledge/rules.js";
13
+ const FILE_ORDER = [GUIDE_FILE, DETAILED_GUIDE_FILE, INSTRUCTIONS_FILE];
14
+ /** The second line under a rule: its pull requests with the newest merge
15
+ * month, or its instruction file lines. */
12
16
  function sourcesLine(entry) {
13
17
  if (entry.sources.length === 0)
14
18
  return "no sources";
15
- return entry.sources.map(sourceLabel).join(" · ");
19
+ const pulls = entry.sources.filter((source) => "pr" in source);
20
+ if (pulls.length === 0) {
21
+ return entry.sources.map(sourceLabel).join(" · ");
22
+ }
23
+ const numbers = pulls.map(sourceLabel).join(", ");
24
+ const months = pulls
25
+ .map((source) => source.mergedAt?.slice(0, 7))
26
+ .filter((month) => Boolean(month))
27
+ .sort();
28
+ const newest = months.at(-1);
29
+ if (pulls.length === 1) {
30
+ return [numbers, newest, "1 PR"].filter(Boolean).join(" · ");
31
+ }
32
+ return newest ? `${numbers} · newest ${newest}` : numbers;
16
33
  }
17
34
  /** The human listing, grouped by the file each rule lives in. */
18
35
  export function renderSources(file) {
@@ -385,6 +385,7 @@ async function pullRequests(client, options, previous, phase) {
385
385
  body: String(pr.body ?? ""),
386
386
  state: String(pr.state ?? ""),
387
387
  merged: Boolean(pr.merged_at),
388
+ ...(pr.merged_at ? { mergedAt: String(pr.merged_at) } : {}),
388
389
  updatedAt: String(pr.updated_at ?? ""),
389
390
  headSha: String(pr.head?.sha ?? ""),
390
391
  labels: Array.isArray(pr.labels)
@@ -1,8 +1,16 @@
1
1
  import type { AiProvider, AiResponse, Options } from "../types.ts";
2
2
  import type { Fact } from "./types.ts";
3
+ import { type GuideFileCount, type GuideRule } from "./guide_ids.ts";
3
4
  export type ReviewDocuments = {
4
5
  guide: string;
5
6
  detailed?: string;
7
+ /** Every check line that got an `R` id, with the pull requests of the
8
+ * findings it merges. */
9
+ rules?: (GuideRule & {
10
+ pullRequests: number[];
11
+ })[];
12
+ /** Check lines and how many of them got an id, per file. */
13
+ counts?: GuideFileCount[];
6
14
  };
7
15
  type UsageSink = (job: string, response: AiResponse) => Promise<void>;
8
16
  /** A fact read out of a single pull request describes that request, not the
@@ -22,6 +30,9 @@ export declare function validateGuide(text: string, options?: {
22
30
  minPasses?: number;
23
31
  maxPasses?: number;
24
32
  }): string | null;
33
+ /** The pull requests behind each finding in `guideMaterial`, by position, so
34
+ * finding `n` is `[n - 1]`. A review finding's evidence is `PR #12`. */
35
+ export declare function findingPullRequests(facts: Fact[]): number[][];
25
36
  /** Builds the review method with the high model. Returns `undefined` below the
26
37
  * signal threshold, which is a data condition, not an AI failure. There is no
27
38
  * deterministic fallback: a failed or unusable generation fails the run. */
@@ -1,5 +1,6 @@
1
1
  import { AiBatch } from "../ai/batch.js";
2
2
  import { log } from "../util/log.js";
3
+ import { assignGuideIds, } from "./guide_ids.js";
3
4
  /** A fact read out of a single pull request describes that request, not the
4
5
  * repository. `origin` is absent on facts written before the field existed, so
5
6
  * those count as repository policy. */
@@ -133,7 +134,10 @@ export function validateGuide(text, options = {}) {
133
134
  function guideMaterial(facts) {
134
135
  const findings = guideFindings(facts)
135
136
  .slice(0, MAX_FINDINGS)
136
- .map((item) => ({
137
+ .map((item, index) => ({
138
+ // The number the guide lines cite. The pull requests behind it stay
139
+ // out of the prompt, in `findingPullRequests`.
140
+ number: index + 1,
137
141
  class: (item.class ?? "general").trim() || "general",
138
142
  rule: item.claim,
139
143
  ...(item.trigger ? { trigger: item.trigger } : {}),
@@ -144,13 +148,25 @@ function guideMaterial(facts) {
144
148
  }));
145
149
  return JSON.stringify(findings, null, 2);
146
150
  }
151
+ /** The pull requests behind each finding in `guideMaterial`, by position, so
152
+ * finding `n` is `[n - 1]`. A review finding's evidence is `PR #12`. */
153
+ export function findingPullRequests(facts) {
154
+ return guideFindings(facts)
155
+ .slice(0, MAX_FINDINGS)
156
+ .map((item) => [
157
+ ...new Set(item.evidence.flatMap((evidence) => {
158
+ const match = /^PR #(\d+)$/.exec(evidence.trim());
159
+ return match ? [Number(match[1])] : [];
160
+ })),
161
+ ]);
162
+ }
147
163
  const GUIDE_SYSTEM = `You write a code-review method for an unfamiliar open-source repository.
148
164
  Ground every check in the supplied findings. Never invent a file, path, command, or policy. Never write a pull-request number, a commit id, a reviewer name, a mention, a quoted comment, or an attribution. Never add a priority tag. Never tell the reader to run a command.`;
149
165
  const CONSOLIDATE = `- Consolidate the findings into a small set of coherent passes: group related findings, merge near-duplicates, and use between 3 and 12 passes. Represent every finding; never drop one to hit the pass count.
150
166
  - Name each pass in Title Case. Never a lowercase slug such as "test-cleanup".
151
167
  - Every rule is a general invariant a future change must satisfy, not a description of one past fix. Keep the specific case only as the example under it.`;
152
168
  const CHECK_SHAPE = `- Under each pass, write each rule as one general invariant line, then its concrete case indented under it:
153
- - <when <trigger> changes, <obligation>, or every <surface> must ...> · <why it matters here>
169
+ - <when <trigger> changes, <obligation>, or every <surface> must ...> · <why it matters here> [<finding numbers>]
154
170
  - <the concrete case: what changed and where>
155
171
  - Give each pass a \`**Goal:**\` line and an \`**Applies to:**\` line.
156
172
  - End each pass with \`**Exit check:**\` followed by its obligations, one per line, so a reviewer who sees only a diff can apply the rule:
@@ -166,6 +182,7 @@ function fullGuideRequest(material) {
166
182
  - Start with one \`#\` title, one sentence of purpose, and one line on how to use the method.
167
183
  ${CONSOLIDATE}
168
184
  ${CHECK_SHAPE}
185
+ - End every rule line with the numbers of the findings it merges, in square brackets, for example [3, 17]. Each finding has a "number". Put these brackets on no other line.
169
186
  - No priority tags. No commands. No code fences. Return only the Markdown.
170
187
 
171
188
  FINDINGS:
@@ -183,9 +200,10 @@ function shortGuideRequest(material, full) {
183
200
  [PR_REVIEW_DETAILED_GUIDE.md](PR_REVIEW_DETAILED_GUIDE.md) for the full method.
184
201
  ${CONSOLIDATE}
185
202
  - Keep the highest-value checks, one per line, in the same shape:
186
- - <what to check or require> · <why it matters here>
203
+ - <what to check or require> · <why it matters here> [<finding numbers>]
204
+ - End every check line with the bracketed finding numbers of the full-method lines it summarizes, joined into one bracket, for example [3, 17]. Put these brackets on no other line.
187
205
  - End every pass with \`**Exit check:** <one line>\`.
188
- - No priority tags, commands, pull-request numbers, ids, names, mentions or quotes.
206
+ - No priority tags, commands, pull-request numbers, names, mentions or quotes.
189
207
  - Do not use fenced code blocks. Return only the Markdown.
190
208
 
191
209
  FULL METHOD:
@@ -217,15 +235,34 @@ export async function synthesizeReviewGuides(provider, repo, ai, model, concurre
217
235
  log("ai", "synth_guide produced nothing usable; skipping the guide");
218
236
  return undefined;
219
237
  }
238
+ const sources = findingPullRequests(facts);
220
239
  const fullLines = full.split("\n").length;
221
240
  if (fullLines <= DETAIL_THRESHOLD_LINES) {
222
- return { guide: withTrailingNewline(full) };
241
+ return withRuleIds(withTrailingNewline(full), undefined, sources);
223
242
  }
243
+ // The short guide is asked from the full method with its finding brackets
244
+ // still on, so it can carry them over to the lines it summarizes.
224
245
  const [shortResponse] = await queue.run([shortGuideRequest(material, full)], usage);
225
246
  const short = cleanGuide(shortResponse?.text ?? "");
226
247
  if (!short)
227
- return { guide: withTrailingNewline(full) };
228
- return { guide: withTrailingNewline(short), detailed: full };
248
+ return withRuleIds(withTrailingNewline(full), undefined, sources);
249
+ return withRuleIds(withTrailingNewline(short), full, sources);
250
+ }
251
+ /** Replaces the finding brackets with `R` ids and attaches each id's pull
252
+ * requests. */
253
+ function withRuleIds(guide, detailed, sources) {
254
+ const assigned = assignGuideIds(guide, detailed, sources.length);
255
+ return {
256
+ guide: assigned.guide,
257
+ ...(assigned.detailed !== undefined ? { detailed: assigned.detailed } : {}),
258
+ rules: assigned.rules.map((rule) => ({
259
+ ...rule,
260
+ pullRequests: [
261
+ ...new Set(rule.findings.flatMap((n) => sources[n - 1] ?? [])),
262
+ ].sort((a, b) => a - b),
263
+ })),
264
+ counts: assigned.counts,
265
+ };
229
266
  }
230
267
  /** Strips a wrapping code fence and the tokens a guide must never carry (a
231
268
  * priority tag, a mention, a pull-request number), so an otherwise good guide is
@@ -0,0 +1,25 @@
1
+ export type GuideRule = {
2
+ id: string;
3
+ file: string;
4
+ /** The line without its bullet, its id and its backticks. */
5
+ text: string;
6
+ /** 1-based numbers of the findings the line merges, sorted. */
7
+ findings: number[];
8
+ };
9
+ export type GuideFileCount = {
10
+ file: string;
11
+ rules: number;
12
+ withIds: number;
13
+ };
14
+ /** Gives every check line that ends in a usable source list an `R` id,
15
+ * numbered in file order. With a detailed guide, its lines are numbered first
16
+ * and a short-guide line with the same finding set shares that id. A line with
17
+ * no usable source list keeps no id. No other line is changed. */
18
+ export declare function assignGuideIds(guide: string, detailed: string | undefined, findingCount: number): {
19
+ guide: string;
20
+ detailed?: string;
21
+ rules: GuideRule[];
22
+ counts: GuideFileCount[];
23
+ };
24
+ /** `[write] PR_REVIEW_GUIDE.md · 34 rules · 31 with sources`. */
25
+ export declare function guideWriteLine(count: GuideFileCount): string;
@@ -0,0 +1,93 @@
1
+ /** Guide rule ids and the findings each guide line rests on.
2
+ *
3
+ * The guide prompt numbers the findings it is given and asks the model to end
4
+ * every check line with the numbers of the findings it merges, `[3, 17]`.
5
+ * Code then replaces that bracket with an `R` id and remembers the findings,
6
+ * so the pull requests behind a line can be recorded in `RULES.json` without
7
+ * a pull request number or a date ever entering the guide. */
8
+ import { DETAILED_GUIDE_FILE, GUIDE_FILE } from "./rules.js";
9
+ /** The source list the prompt asks for: one bracket of numbers at the very
10
+ * end of the line, after a space. `items[3]` has no space before it, so it is
11
+ * never taken. */
12
+ const SOURCE_BRACKET = /\s+\[\s*(\d+(?:\s*,\s*\d+)*)\s*\]\s*$/;
13
+ /** A top-level `rule · why` bullet, the guide's unit of a check. The link to
14
+ * the detailed file is not a check. */
15
+ function isCheckLine(line) {
16
+ return line.startsWith("- ") && line.includes(" · ") && !line.includes("](");
17
+ }
18
+ /** The finding numbers at the end of a check line and the line without them,
19
+ * or `null` when the line does not end in a source list. A bracket inside
20
+ * inline code is code, not a source list. Every other bracket on the line is
21
+ * left exactly as the model wrote it. */
22
+ function takeSourceBracket(line) {
23
+ const match = SOURCE_BRACKET.exec(line);
24
+ if (!match)
25
+ return null;
26
+ const before = line.slice(0, match.index);
27
+ if ((before.split("`").length - 1) % 2 === 1)
28
+ return null;
29
+ return { numbers: match[1].split(",").map(Number), line: before };
30
+ }
31
+ function setKey(numbers) {
32
+ return numbers.join(",");
33
+ }
34
+ function ruleText(line) {
35
+ return line.replace(/^- /, "").replaceAll("`", "").trim();
36
+ }
37
+ /** Rewrites one guide. `idFor` decides the id of a check line from its
38
+ * finding set, so the short guide can reuse the detailed guide's ids. */
39
+ function rewrite(text, file, findingCount, idFor) {
40
+ let rules = 0;
41
+ let withIds = 0;
42
+ const lines = text.split("\n").map((raw) => {
43
+ if (!isCheckLine(raw))
44
+ return raw;
45
+ rules++;
46
+ const taken = takeSourceBracket(raw);
47
+ if (!taken)
48
+ return raw;
49
+ const valid = [
50
+ ...new Set(taken.numbers.filter((n) => n >= 1 && n <= findingCount)),
51
+ ].sort((a, b) => a - b);
52
+ // A source list that names no real finding is dropped with no id.
53
+ if (valid.length === 0)
54
+ return taken.line;
55
+ withIds++;
56
+ return `${taken.line} [${idFor(valid, taken.line)}]`;
57
+ });
58
+ return { text: lines.join("\n"), count: { file, rules, withIds } };
59
+ }
60
+ /** Gives every check line that ends in a usable source list an `R` id,
61
+ * numbered in file order. With a detailed guide, its lines are numbered first
62
+ * and a short-guide line with the same finding set shares that id. A line with
63
+ * no usable source list keeps no id. No other line is changed. */
64
+ export function assignGuideIds(guide, detailed, findingCount) {
65
+ const rules = [];
66
+ const bySet = new Map();
67
+ const add = (file, numbers, line) => {
68
+ const id = `R${rules.length + 1}`;
69
+ rules.push({ id, file, text: ruleText(line), findings: numbers });
70
+ return id;
71
+ };
72
+ if (detailed === undefined) {
73
+ const single = rewrite(guide, GUIDE_FILE, findingCount, (numbers, line) => add(GUIDE_FILE, numbers, line));
74
+ return { guide: single.text, rules, counts: [single.count] };
75
+ }
76
+ const full = rewrite(detailed, DETAILED_GUIDE_FILE, findingCount, (numbers, line) => {
77
+ const id = add(DETAILED_GUIDE_FILE, numbers, line);
78
+ if (!bySet.has(setKey(numbers)))
79
+ bySet.set(setKey(numbers), id);
80
+ return id;
81
+ });
82
+ const short = rewrite(guide, GUIDE_FILE, findingCount, (numbers, line) => bySet.get(setKey(numbers)) ?? add(GUIDE_FILE, numbers, line));
83
+ return {
84
+ guide: short.text,
85
+ detailed: full.text,
86
+ rules,
87
+ counts: [short.count, full.count],
88
+ };
89
+ }
90
+ /** `[write] PR_REVIEW_GUIDE.md · 34 rules · 31 with sources`. */
91
+ export function guideWriteLine(count) {
92
+ return `${count.file} · ${count.rules} ${count.rules === 1 ? "rule" : "rules"} · ${count.withIds} with sources`;
93
+ }
@@ -1,9 +1,9 @@
1
1
  /** What a `sync` changed in the rules, compared by their sources.
2
2
  *
3
- * A rebuilt `INSTRUCTIONS.md` can reword every rule, so text alone cannot say
4
- * which rule became which. Sources survive a rewrite: an instruction rule
5
- * keeps resting on the same file lines. A new rule that shares a source with
6
- * an old one is that rule, rewritten. */
3
+ * A rebuilt guide can reword every line, so text alone cannot say which line
4
+ * became which. Sources survive a rewrite: a guide line keeps resting on the
5
+ * same pull requests, an instruction rule on the same file lines. A new rule
6
+ * that shares a source with an old one is that rule, rewritten. */
7
7
  import { type RuleEntry } from "./rules.ts";
8
8
  export type AddedRule = {
9
9
  id: string;
@@ -24,6 +24,8 @@ export type DroppedRule = {
24
24
  id: string;
25
25
  text: string;
26
26
  sources: string[];
27
+ /** Pull requests that are no longer in the window this sync read. */
28
+ leftWindow: string[];
27
29
  };
28
30
  export type RuleChanges = {
29
31
  added: AddedRule[];
@@ -31,9 +33,10 @@ export type RuleChanges = {
31
33
  dropped: DroppedRule[];
32
34
  unchanged: number;
33
35
  };
34
- /** Compares one kind of rule. A rule with no source cannot be matched and is
35
- * left out of the report. */
36
- export declare function compareRules(previous: Record<string, RuleEntry> | undefined, next: Record<string, RuleEntry>, kind: "I"): RuleChanges;
37
- /** `1 rule added (AGENTS.md:40) · 1 rewritten (I3, AGENTS.md:12 joined) · 1
38
- * dropped (AGENTS.md:9)`, or `no rule changed`. */
36
+ /** Compares one kind of rule, `R` or `I`. A rule with no source cannot be
37
+ * matched and is left out of the report. `inWindow` names the pull requests
38
+ * the sync read, so a dropped rule can say its pull request left the window. */
39
+ export declare function compareRules(previous: Record<string, RuleEntry> | undefined, next: Record<string, RuleEntry>, kind: "R" | "I", inWindow?: Set<number>): RuleChanges;
40
+ /** `2 rules added (#402, #407) · 1 rewritten (R12, #340 joined) · 1 dropped
41
+ * (#101 left the window)`, or `no rule changed`. */
39
42
  export declare function ruleChangeLine(changes: RuleChanges): string;
@@ -1,16 +1,17 @@
1
1
  /** What a `sync` changed in the rules, compared by their sources.
2
2
  *
3
- * A rebuilt `INSTRUCTIONS.md` can reword every rule, so text alone cannot say
4
- * which rule became which. Sources survive a rewrite: an instruction rule
5
- * keeps resting on the same file lines. A new rule that shares a source with
6
- * an old one is that rule, rewritten. */
3
+ * A rebuilt guide can reword every line, so text alone cannot say which line
4
+ * became which. Sources survive a rewrite: a guide line keeps resting on the
5
+ * same pull requests, an instruction rule on the same file lines. A new rule
6
+ * that shares a source with an old one is that rule, rewritten. */
7
7
  import { rulesOfKind, sourceLabel } from "./rules.js";
8
8
  function labels(entry) {
9
9
  return [...new Set(entry.sources.map(sourceLabel))];
10
10
  }
11
- /** Compares one kind of rule. A rule with no source cannot be matched and is
12
- * left out of the report. */
13
- export function compareRules(previous, next, kind) {
11
+ /** Compares one kind of rule, `R` or `I`. A rule with no source cannot be
12
+ * matched and is left out of the report. `inWindow` names the pull requests
13
+ * the sync read, so a dropped rule can say its pull request left the window. */
14
+ export function compareRules(previous, next, kind, inWindow) {
14
15
  const old = Object.entries(rulesOfKind(previous, kind))
15
16
  .map(([id, entry]) => ({ id, entry, sources: labels(entry) }))
16
17
  .filter((rule) => rule.sources.length > 0);
@@ -58,6 +59,12 @@ export function compareRules(previous, next, kind) {
58
59
  id: rule.id,
59
60
  text: rule.entry.text,
60
61
  sources: rule.sources,
62
+ leftWindow: inWindow
63
+ ? rule.sources.filter((source) => {
64
+ const match = /^#(\d+)$/.exec(source);
65
+ return match !== null && !inWindow.has(Number(match[1]));
66
+ })
67
+ : [],
61
68
  });
62
69
  }
63
70
  return changes;
@@ -69,8 +76,8 @@ function listed(items, max = 5) {
69
76
  return unique.join(", ");
70
77
  return `${unique.slice(0, max).join(", ")}, and ${unique.length - max} more`;
71
78
  }
72
- /** `1 rule added (AGENTS.md:40) · 1 rewritten (I3, AGENTS.md:12 joined) · 1
73
- * dropped (AGENTS.md:9)`, or `no rule changed`. */
79
+ /** `2 rules added (#402, #407) · 1 rewritten (R12, #340 joined) · 1 dropped
80
+ * (#101 left the window)`, or `no rule changed`. */
74
81
  export function ruleChangeLine(changes) {
75
82
  const parts = [];
76
83
  if (changes.added.length > 0) {
@@ -84,7 +91,8 @@ export function ruleChangeLine(changes) {
84
91
  parts.push(`${changes.rewritten.length} rewritten (${listed(items, 3)})`);
85
92
  }
86
93
  if (changes.dropped.length > 0) {
87
- parts.push(`${changes.dropped.length} dropped (${listed(changes.dropped.flatMap((rule) => rule.sources))})`);
94
+ const items = changes.dropped.flatMap((rule) => rule.sources.map((source) => rule.leftWindow.includes(source) ? `${source} left the window` : source));
95
+ parts.push(`${changes.dropped.length} dropped (${listed(items)})`);
88
96
  }
89
97
  return parts.length > 0 ? parts.join(" · ") : "no rule changed";
90
98
  }
@@ -1,14 +1,22 @@
1
- /** `RULES.json`: every instruction rule's id, text and sources.
1
+ /** `RULES.json`: every guide and instruction rule's id, text and sources.
2
2
  *
3
- * `INSTRUCTIONS.md` carries only a short id per rule (`[I1]`). Where a rule
4
- * came from (instruction file lines) lives here, outside the prompt, so the
5
- * guide block stays byte stable for the prompt cache. Written in the guide
3
+ * The guides carry only a short id per rule (`[R12]`, `[I1]`). Where a rule
4
+ * came from (pull requests and their merge dates, instruction file lines) lives
5
+ * here, outside the prompt, so the guide block stays byte stable for the
6
+ * prompt cache and dates never reach the model. Written in the guide
6
7
  * directory under the knowledge lock with the guides, so an id and its text
7
8
  * always come from one build. */
8
9
  export declare const RULES_FILE = "RULES.json";
9
10
  export declare const INSTRUCTIONS_FILE = "INSTRUCTIONS.md";
10
- /** An instruction rule rests on lines of an instruction file. */
11
+ export declare const GUIDE_FILE = "PR_REVIEW_GUIDE.md";
12
+ export declare const DETAILED_GUIDE_FILE = "PR_REVIEW_DETAILED_GUIDE.md";
13
+ /** A guide rule rests on pull requests, an instruction rule on lines of an
14
+ * instruction file. `mergedAt` is a `YYYY-MM-DD` date, missing for an
15
+ * unmerged pull request or one cached before the date was kept. */
11
16
  export type RuleSource = {
17
+ pr: number;
18
+ mergedAt?: string;
19
+ } | {
12
20
  path: string;
13
21
  line: number;
14
22
  };
@@ -28,17 +36,19 @@ export type RulesFile = {
28
36
  builtAt: string;
29
37
  rules: Record<string, RuleEntry>;
30
38
  };
31
- /** Ids are `I` for instruction rules, then a number. `C` is kept for built-in
32
- * checks. */
39
+ /** Ids are `R` for guide rules and `I` for instruction rules, then a number.
40
+ * `C` is kept for built-in checks. */
33
41
  export declare const RULE_ID: RegExp;
34
42
  /** The parsed file, or `null` when it is missing, not JSON, or not this
35
43
  * schema. An entry that does not fit is skipped rather than losing the rest. */
36
44
  export declare function parseRules(text: string): RulesFile | null;
37
- /** Ids in reading order, by number. */
45
+ /** Ids in reading order: guide rules, then instruction rules, each by number. */
38
46
  export declare function sortedRuleIds(rules: Record<string, RuleEntry>): string[];
39
47
  export declare function rulesFileText(file: RulesFile): string;
40
- /** The rules of one kind, by id prefix. */
41
- export declare function rulesOfKind(rules: Record<string, RuleEntry> | undefined, kind: "I"): Record<string, RuleEntry>;
42
- /** `AGENTS.md:31`: one source as a reader writes it, and as the change report
43
- * compares it. */
48
+ /** The rules of one kind, `R` or `I`. */
49
+ export declare function rulesOfKind(rules: Record<string, RuleEntry> | undefined, kind: "R" | "I"): Record<string, RuleEntry>;
50
+ /** `#212` or `AGENTS.md:31`: one source as a reader writes it, and as the
51
+ * change report compares it. */
44
52
  export declare function sourceLabel(source: RuleSource): string;
53
+ /** `2026-03-04` from an ISO timestamp, or `undefined` when there is none. */
54
+ export declare function mergedDate(iso: string | undefined): string | undefined;
@@ -1,19 +1,25 @@
1
- /** `RULES.json`: every instruction rule's id, text and sources.
1
+ /** `RULES.json`: every guide and instruction rule's id, text and sources.
2
2
  *
3
- * `INSTRUCTIONS.md` carries only a short id per rule (`[I1]`). Where a rule
4
- * came from (instruction file lines) lives here, outside the prompt, so the
5
- * guide block stays byte stable for the prompt cache. Written in the guide
3
+ * The guides carry only a short id per rule (`[R12]`, `[I1]`). Where a rule
4
+ * came from (pull requests and their merge dates, instruction file lines) lives
5
+ * here, outside the prompt, so the guide block stays byte stable for the
6
+ * prompt cache and dates never reach the model. Written in the guide
6
7
  * directory under the knowledge lock with the guides, so an id and its text
7
8
  * always come from one build. */
8
9
  export const RULES_FILE = "RULES.json";
9
10
  export const INSTRUCTIONS_FILE = "INSTRUCTIONS.md";
10
- /** Ids are `I` for instruction rules, then a number. `C` is kept for built-in
11
- * checks. */
12
- export const RULE_ID = /^I[1-9]\d*$/;
11
+ export const GUIDE_FILE = "PR_REVIEW_GUIDE.md";
12
+ export const DETAILED_GUIDE_FILE = "PR_REVIEW_DETAILED_GUIDE.md";
13
+ /** Ids are `R` for guide rules and `I` for instruction rules, then a number.
14
+ * `C` is kept for built-in checks. */
15
+ export const RULE_ID = /^[RI][1-9]\d*$/;
13
16
  function isSource(value) {
14
17
  if (!value || typeof value !== "object")
15
18
  return false;
16
19
  const record = value;
20
+ if (typeof record.pr === "number") {
21
+ return record.mergedAt === undefined || typeof record.mergedAt === "string";
22
+ }
17
23
  return typeof record.path === "string" && typeof record.line === "number";
18
24
  }
19
25
  /** The parsed file, or `null` when it is missing, not JSON, or not this
@@ -61,9 +67,10 @@ export function parseRules(text) {
61
67
  function idNumber(id) {
62
68
  return Number(id.slice(1));
63
69
  }
64
- /** Ids in reading order, by number. */
70
+ /** Ids in reading order: guide rules, then instruction rules, each by number. */
65
71
  export function sortedRuleIds(rules) {
66
- return Object.keys(rules).sort((a, b) => idNumber(a) - idNumber(b));
72
+ const kind = (id) => (id.startsWith("R") ? 0 : 1);
73
+ return Object.keys(rules).sort((a, b) => kind(a) - kind(b) || idNumber(a) - idNumber(b));
67
74
  }
68
75
  export function rulesFileText(file) {
69
76
  const rules = {};
@@ -71,12 +78,16 @@ export function rulesFileText(file) {
71
78
  rules[id] = file.rules[id];
72
79
  return `${JSON.stringify({ ...file, rules }, null, 2)}\n`;
73
80
  }
74
- /** The rules of one kind, by id prefix. */
81
+ /** The rules of one kind, `R` or `I`. */
75
82
  export function rulesOfKind(rules, kind) {
76
83
  return Object.fromEntries(Object.entries(rules ?? {}).filter(([id]) => id.startsWith(kind)));
77
84
  }
78
- /** `AGENTS.md:31`: one source as a reader writes it, and as the change report
79
- * compares it. */
85
+ /** `#212` or `AGENTS.md:31`: one source as a reader writes it, and as the
86
+ * change report compares it. */
80
87
  export function sourceLabel(source) {
81
- return `${source.path}:${source.line}`;
88
+ return "pr" in source ? `#${source.pr}` : `${source.path}:${source.line}`;
89
+ }
90
+ /** `2026-03-04` from an ISO timestamp, or `undefined` when there is none. */
91
+ export function mergedDate(iso) {
92
+ return iso && /^\d{4}-\d{2}-\d{2}/.test(iso) ? iso.slice(0, 10) : undefined;
82
93
  }
@@ -5,6 +5,9 @@ export type PullRequest = {
5
5
  body: string;
6
6
  state: string;
7
7
  merged: boolean;
8
+ /** When the pull request was merged, from the listing. Missing on an
9
+ * unmerged pull request and on rows cached before the field existed. */
10
+ mergedAt?: string;
8
11
  updatedAt: string;
9
12
  headSha: string;
10
13
  labels: string[];
@@ -1,3 +1,4 @@
1
+ import type { ReviewDocuments } from "../knowledge/guide.ts";
1
2
  import { type InstructionCounts, type InstructionsResult } from "../knowledge/instructions.ts";
2
3
  import { type RuleChanges } from "../knowledge/rule_changes.ts";
3
4
  import type { Source } from "../knowledge/types.ts";
@@ -25,22 +26,24 @@ export type RulesWriteResult = {
25
26
  rules: number;
26
27
  /** `null` when there was no earlier `RULES.json` to compare with. */
27
28
  changes: {
29
+ guide: RuleChanges;
28
30
  instructions: RuleChanges;
29
31
  } | null;
30
- /** False when the instructions were skipped and there was no earlier
31
- * `INSTRUCTIONS.md` or `RULES.json`: nothing happened that the run's output
32
- * should mention, so a repository without instruction files sees the same
33
- * output as before. */
32
+ /** False when nothing happened that the run's output should mention: the
33
+ * instructions were skipped, no guide rule was built, and there was no
34
+ * earlier `INSTRUCTIONS.md` or `RULES.json`. */
34
35
  reported: boolean;
35
36
  };
36
37
  /** Writes or removes `INSTRUCTIONS.md`, writes `RULES.json`, and reports
37
38
  * what changed since the last build. The caller holds the knowledge lock, so
38
- * the ids here and the files beside them belong to one build. */
39
+ * the ids here and the guides just written belong to one build. */
39
40
  export declare function writeInstructionsAndRules(input: {
40
41
  repo: string;
41
42
  /** `init` names a skip even with nothing to remove, so a first build says
42
43
  * why it has no `INSTRUCTIONS.md`. A `sync` stays quiet then. */
43
44
  command: "init" | "remake" | "probe" | "review";
45
+ documents: ReviewDocuments | undefined;
46
+ signalCount: number;
44
47
  instructions: InstructionsOutcome;
45
48
  source: Source;
46
49
  }): Promise<RulesWriteResult>;
@@ -4,10 +4,11 @@
4
4
  * instructions and one call, under the knowledge lock, to write them with the
5
5
  * rules. */
6
6
  import { reposDir } from "../config.js";
7
+ import { guideWriteLine } from "../knowledge/guide_ids.js";
7
8
  import { agentInstructionsLimit, DEFAULT_AGENT_INSTRUCTIONS, } from "../knowledge/instruction_files.js";
8
9
  import { instructionRuleEntries, instructionsWriteLine, synthesizeInstructions, } from "../knowledge/instructions.js";
9
10
  import { compareRules, ruleChangeLine, } from "../knowledge/rule_changes.js";
10
- import { INSTRUCTIONS_FILE, parseRules, RULES_FILE, rulesFileText, rulesOfKind, } from "../knowledge/rules.js";
11
+ import { INSTRUCTIONS_FILE, mergedDate, parseRules, RULES_FILE, rulesFileText, rulesOfKind, } from "../knowledge/rules.js";
11
12
  import { log, timed } from "../util/log.js";
12
13
  import { readTextFile, remove, stat } from "../util/runtime.js";
13
14
  /** Why no instructions are built this run, or `null` when they are. */
@@ -80,26 +81,54 @@ async function readRulesFile(repo) {
80
81
  return null;
81
82
  }
82
83
  }
84
+ /** The `R` entries for this build. A guide this run wrote brings its own. A
85
+ * guide kept from the last run (the AI produced none) keeps the last run's
86
+ * ids. A guide that was removed has none. */
87
+ function guideEntries(documents, signalCount, previous, source) {
88
+ if (!documents) {
89
+ return signalCount > 2 ? rulesOfKind(previous, "R") : {};
90
+ }
91
+ const mergedAt = new Map(source.pullRequests.map((pr) => [pr.number, mergedDate(pr.mergedAt)]));
92
+ return Object.fromEntries((documents.rules ?? []).map((rule) => [
93
+ rule.id,
94
+ {
95
+ file: rule.file,
96
+ text: rule.text,
97
+ sources: rule.pullRequests.map((pr) => {
98
+ const date = mergedAt.get(pr);
99
+ return date ? { pr, mergedAt: date } : { pr };
100
+ }),
101
+ },
102
+ ]));
103
+ }
83
104
  function instructionsLine(counts) {
84
105
  const dropped = counts.unsupportedSource + counts.unknownName;
85
106
  return `${INSTRUCTIONS_FILE} skipped: the instruction files hold no rule a reviewer can check · ${dropped} dropped · ${counts.overCap} over the cap`;
86
107
  }
87
108
  /** Writes or removes `INSTRUCTIONS.md`, writes `RULES.json`, and reports
88
109
  * what changed since the last build. The caller holds the knowledge lock, so
89
- * the ids here and the files beside them belong to one build. */
110
+ * the ids here and the guides just written belong to one build. */
90
111
  export async function writeInstructionsAndRules(input) {
91
- const { repo, instructions, source } = input;
112
+ const { repo, documents, instructions, source } = input;
92
113
  const directory = `${reposDir()}/${repo}`;
93
114
  const { writeTextFileAtomic } = await import("../util/atomic.js");
94
115
  const previous = await readRulesFile(repo);
95
116
  const hadInstructions = await exists(`${directory}/${INSTRUCTIONS_FILE}`);
96
117
  const hadRules = await exists(`${directory}/${RULES_FILE}`);
97
- if (instructions.status === "skipped" && !hadInstructions && !hadRules) {
118
+ const guideRules = guideEntries(documents, input.signalCount, previous?.rules, source);
119
+ if (instructions.status === "skipped" &&
120
+ !hadInstructions &&
121
+ !hadRules &&
122
+ Object.keys(guideRules).length === 0 &&
123
+ (documents?.counts ?? []).length === 0) {
98
124
  if (input.command === "init") {
99
125
  log("write", `${INSTRUCTIONS_FILE} skipped: ${instructions.reason}`);
100
126
  }
101
127
  return { rules: 0, changes: null, reported: false };
102
128
  }
129
+ for (const count of documents?.counts ?? []) {
130
+ log("write", guideWriteLine(count));
131
+ }
103
132
  let instructionRules = {};
104
133
  switch (instructions.status) {
105
134
  case "written": {
@@ -126,10 +155,14 @@ export async function writeInstructionsAndRules(input) {
126
155
  break;
127
156
  case "skipped":
128
157
  await remove(`${directory}/${INSTRUCTIONS_FILE}`).catch(() => { });
129
- log("write", `${INSTRUCTIONS_FILE} skipped: ${instructions.reason}`);
158
+ // Guide rules bring every repository here, so the skip is only named
159
+ // when a file was removed or on a first build.
160
+ if (hadInstructions || input.command === "init") {
161
+ log("write", `${INSTRUCTIONS_FILE} skipped: ${instructions.reason}`);
162
+ }
130
163
  break;
131
164
  }
132
- const rules = { ...instructionRules };
165
+ const rules = { ...guideRules, ...instructionRules };
133
166
  if (Object.keys(rules).length > 0) {
134
167
  await writeTextFileAtomic(`${directory}/${RULES_FILE}`, rulesFileText({
135
168
  schemaVersion: 1,
@@ -144,12 +177,19 @@ export async function writeInstructionsAndRules(input) {
144
177
  if (!previous) {
145
178
  return { rules: Object.keys(rules).length, changes: null, reported: true };
146
179
  }
180
+ const inWindow = new Set(source.pullRequests.map((pr) => pr.number));
147
181
  const changes = {
182
+ guide: compareRules(previous.rules, rules, "R", inWindow),
148
183
  instructions: compareRules(previous.rules, rules, "I"),
149
184
  };
150
- if (Object.keys(rulesOfKind(previous.rules, "I")).length > 0 ||
151
- Object.keys(rules).length > 0) {
152
- log("instructions", ruleChangeLine(changes.instructions));
185
+ for (const [phase, kind, change] of [
186
+ ["guide", "R", changes.guide],
187
+ ["instructions", "I", changes.instructions],
188
+ ]) {
189
+ const any = Object.keys(rulesOfKind(previous.rules, kind)).length > 0 ||
190
+ Object.keys(rulesOfKind(rules, kind)).length > 0;
191
+ if (any)
192
+ log(phase, ruleChangeLine(change));
153
193
  }
154
194
  return { rules: Object.keys(rules).length, changes, reported: true };
155
195
  }
@@ -367,6 +367,8 @@ async function initOrRemake(options) {
367
367
  rulesResult = await writeInstructionsAndRules({
368
368
  repo: options.repo,
369
369
  command: options.command,
370
+ documents: reviewDocuments,
371
+ signalCount: reviewSignalCount(facts),
370
372
  instructions,
371
373
  source,
372
374
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "co-maintainer",
3
- "version": "0.7.0-beta.4",
3
+ "version": "0.7.1-beta.1",
4
4
  "description": "An imitator of yours, A PR review tool like co-maintainer.",
5
5
  "keywords": [
6
6
  "ai",