@open-cr-agent/core 0.12.0 → 0.14.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.
@@ -0,0 +1,19 @@
1
+ export declare const GUIDELINE_SCOPES: readonly ["all", "matched", "reviewer"];
2
+ export type GuidelineScope = (typeof GUIDELINE_SCOPES)[number];
3
+ export interface GuidelineSection {
4
+ heading: string;
5
+ raw: string;
6
+ scope: string[];
7
+ }
8
+ export interface GuidelineSelection {
9
+ given: GuidelineSection[];
10
+ left: GuidelineSection[];
11
+ }
12
+ export declare function guidelineSections(text: string): GuidelineSection[];
13
+ export declare function selectGuidelines(sections: readonly GuidelineSection[], files: readonly string[] | "all", maxChars: number): GuidelineSelection;
14
+ export declare const MAX_GUIDELINES_CHARS = 20000;
15
+ export interface TaskGuidelines {
16
+ text: string;
17
+ left: string[];
18
+ }
19
+ export declare function guidelinesForTask(sections: readonly GuidelineSection[], scope: GuidelineScope, files: readonly string[], checksGuidelines: boolean): TaskGuidelines | undefined;
@@ -0,0 +1,97 @@
1
+ // The repository's guidelines (AGENTS.md) as whole sections, and which of
2
+ // them a review task is given (ADR-0059). A section is never cut: one that
3
+ // does not fit the budget is left out and listed by its heading.
4
+ export const GUIDELINE_SCOPES = ["all", "matched", "reviewer"];
5
+ // A section starts at a heading of level 1 to 3 outside a code fence; what
6
+ // precedes the first heading is a section of its own. A section takes the
7
+ // scope of the heading above it when its own heading names no path.
8
+ export function guidelineSections(text) {
9
+ const sections = [];
10
+ const scopes = [];
11
+ let heading = "";
12
+ let scope = [];
13
+ let lines = [];
14
+ let fenced = false;
15
+ const flush = () => {
16
+ if (lines.length > 0)
17
+ sections.push({ heading, raw: lines.join("\n"), scope });
18
+ };
19
+ for (const line of text.split("\n")) {
20
+ if (/^\s*(```|~~~)/.test(line))
21
+ fenced = !fenced;
22
+ const match = fenced ? null : /^(#{1,3})\s+(.+?)\s*#*\s*$/.exec(line);
23
+ if (match) {
24
+ flush();
25
+ const level = match[1]?.length ?? 1;
26
+ heading = match[2] ?? "";
27
+ const own = pathsIn(heading);
28
+ // The scope each open heading level gives the sections below it.
29
+ while (scopes.length < level - 1)
30
+ scopes.push(scopes.at(-1) ?? []);
31
+ scopes.length = level - 1;
32
+ scope = own.length > 0 ? own : (scopes.at(-1) ?? []);
33
+ scopes.push(scope);
34
+ lines = [];
35
+ }
36
+ lines.push(line);
37
+ }
38
+ flush();
39
+ return sections;
40
+ }
41
+ // A section is about one part of the repository only when its heading says
42
+ // so with a path ("## web/", "### `packages/core`"). Paths in a section's
43
+ // text are mostly examples of a rule that applies everywhere, so they never
44
+ // scope it: recall over tokens.
45
+ const PATH_TOKEN = /(?<![\w.:/@-])((?:[\w.-]+\/)+[\w.-]*)(?![\w/])/g;
46
+ function pathsIn(heading) {
47
+ return [...heading.matchAll(PATH_TOKEN)]
48
+ .map((m) => (m[1] ?? "").replace(/\/$/, ""))
49
+ .filter((p) => p !== "" && !p.startsWith("../"));
50
+ }
51
+ function applies(section, files) {
52
+ if (section.scope.length === 0)
53
+ return true;
54
+ return section.scope.some((scope) => {
55
+ const s = scope.toLowerCase();
56
+ return files.some((file) => {
57
+ const f = file.toLowerCase();
58
+ return f === s || f.startsWith(`${s}/`) || f.endsWith(`/${s}`);
59
+ });
60
+ });
61
+ }
62
+ // In the document's order, every section that applies and still fits.
63
+ export function selectGuidelines(sections, files, maxChars) {
64
+ const given = [];
65
+ const left = [];
66
+ let used = 0;
67
+ for (const section of sections) {
68
+ const cost = section.raw.length + (given.length > 0 ? 1 : 0);
69
+ if ((files === "all" || applies(section, files)) && used + cost <= maxChars) {
70
+ given.push(section);
71
+ used += cost;
72
+ }
73
+ else {
74
+ left.push(section);
75
+ }
76
+ }
77
+ return { given, left };
78
+ }
79
+ export const MAX_GUIDELINES_CHARS = 20_000;
80
+ // What one review task is given. A reviewer that checks the guidelines
81
+ // themselves gets every section whatever the scope.
82
+ export function guidelinesForTask(sections, scope, files, checksGuidelines) {
83
+ if (sections.length === 0)
84
+ return undefined;
85
+ if (scope === "reviewer" && !checksGuidelines)
86
+ return undefined;
87
+ const wanted = scope === "matched" && !checksGuidelines ? files : "all";
88
+ const { given, left } = selectGuidelines(sections, wanted, MAX_GUIDELINES_CHARS);
89
+ // When even the first section that applies is larger than the whole
90
+ // budget, the prompt cuts and marks it, rather than leave it all out.
91
+ if (given.length === 0) {
92
+ const applicable = wanted === "all" ? sections : sections.filter((s) => applies(s, wanted));
93
+ const whole = applicable.map((s) => s.raw).join("\n");
94
+ return whole.trim() ? { text: whole, left: [] } : undefined;
95
+ }
96
+ return { text: given.map((s) => s.raw).join("\n"), left: left.map((s) => s.heading) };
97
+ }
package/dist/index.d.ts CHANGED
@@ -4,6 +4,7 @@ export { SpendLimitReached } from "./agent/spend-limit.js";
4
4
  export { addUsage, emptyUsage } from "./agent/usage.js";
5
5
  export type { AgentEvent, AgentRuntime, AgentTaskSpec, AppliedSampling, AppliedSettings, AttemptRecord, CodeMatch, CompletionRequest, CompletionResult, Effort, FileSymbols, IncompleteEnding, ModelChains, ModelTier, ReferenceIndex, ReviewContext, Sampling, SymbolDefinition, SymbolExtractor, SymbolKind, SymbolReference, SyntaxChecker, Usage, } from "./contracts.js";
6
6
  export { MODEL_TIERS, SYMBOL_KINDS } from "./contracts.js";
7
+ export { GUIDELINE_SCOPES, type GuidelineScope } from "./docs/guidelines.js";
7
8
  export { PROJECT_DOC_LIMITS, type ProjectDoc, type ProjectDocUse, } from "./docs/project-docs.js";
8
9
  export type { AnchorMethod, ChangeRequest, DiffLine, FileChangeKind, FileDiff, Finding, FindingFix, FindingProvenance, FindingStatus, Hunk, LineRange, PriorFinding, PriorReview, QuoteSignature, ReportedFinding, RiskTier, Severity, TaskFinding, Verdict, Verification, } from "./domain.js";
9
10
  export { CompletionError, errorMessage, isOcraError, OCRA_ERROR_CODES, OcraError, type OcraErrorCode, } from "./errors.js";
package/dist/index.js CHANGED
@@ -7,6 +7,7 @@ export { EFFORT_LEVELS, } from "./agent/settings.js";
7
7
  export { SpendLimitReached } from "./agent/spend-limit.js";
8
8
  export { addUsage, emptyUsage } from "./agent/usage.js";
9
9
  export { MODEL_TIERS, SYMBOL_KINDS } from "./contracts.js";
10
+ export { GUIDELINE_SCOPES } from "./docs/guidelines.js";
10
11
  export { PROJECT_DOC_LIMITS, } from "./docs/project-docs.js";
11
12
  export { CompletionError, errorMessage, isOcraError, OCRA_ERROR_CODES, OcraError, } from "./errors.js";
12
13
  export { FIX_REJECTIONS } from "./fix/check.js";
@@ -79,6 +79,7 @@ function executeOptions({ options, settings, spendLimit, signal, emit }, relocat
79
79
  (async (request) => spendLimit.mayCall() ? relocator(request) : undefined),
80
80
  ultra: settings.ultra,
81
81
  without: settings.without,
82
+ guidelineScope: settings.guidelineScope,
82
83
  symbols: options.symbols,
83
84
  references: options.references,
84
85
  plans: new Map(),
@@ -1,6 +1,7 @@
1
1
  import { type AgentSettings } from "../agent/settings.js";
2
2
  import { type AnchorContext } from "../anchor/anchor.js";
3
3
  import type { AgentRuntime, ReferenceIndex, SymbolExtractor, Usage } from "../contracts.js";
4
+ import type { GuidelineScope } from "../docs/guidelines.js";
4
5
  import type { Finding } from "../domain.js";
5
6
  import type { MatrixCell } from "../matrix/matrix.js";
6
7
  import type { ReviewEvent, TaskOutcome } from "../report/report.js";
@@ -19,6 +20,7 @@ export interface ExecuteOptions {
19
20
  runtime: AgentRuntime;
20
21
  ultra?: boolean;
21
22
  without?: ReadonlySet<OptionalContext>;
23
+ guidelineScope?: GuidelineScope;
22
24
  securityFiles?: ReadonlySet<string>;
23
25
  taskTimeoutMs: number;
24
26
  abortGraceMs?: number | undefined;
@@ -18,6 +18,7 @@ function settingsOf(options) {
18
18
  ultra: options.ultra === true,
19
19
  securityFiles: options.securityFiles ?? new Set(),
20
20
  ...(options.without ? { without: options.without } : {}),
21
+ ...(options.guidelineScope ? { guidelineScope: options.guidelineScope } : {}),
21
22
  };
22
23
  }
23
24
  // Runs one (bundle, reviewer) cell and anchors what it reports.
@@ -3,6 +3,7 @@ import type { AnchorContext } from "../anchor/anchor.js";
3
3
  import type { BundlePolicy } from "../bundle/bundle.js";
4
4
  import type { FileGrouper } from "../bundle/grouping.js";
5
5
  import type { AgentRuntime, ModelChains, ReferenceIndex, SymbolExtractor, SyntaxChecker } from "../contracts.js";
6
+ import { type GuidelineScope } from "../docs/guidelines.js";
6
7
  import type { ProjectDoc } from "../docs/project-docs.js";
7
8
  import type { Learning } from "../knowledge/learning.js";
8
9
  import type { MemoryEntry } from "../memory/memory.js";
@@ -29,6 +30,7 @@ export interface ReviewOptions {
29
30
  readTrusted?: (path: string) => Promise<string | undefined>;
30
31
  accountMemory?: readonly MemoryEntry[];
31
32
  learnings?: readonly Learning[];
33
+ guidelineScope?: GuidelineScope;
32
34
  linkedTasks?: boolean;
33
35
  taskSources?: readonly TaskSource[];
34
36
  projectDocs?: readonly ProjectDoc[];
@@ -96,6 +98,7 @@ export interface RunSettings {
96
98
  walkthrough: boolean;
97
99
  without: ReadonlySet<OptionalContext>;
98
100
  fixes: boolean;
101
+ guidelineScope: GuidelineScope;
99
102
  }
100
- export declare function runSettings(options: Pick<ReviewOptions, "limits" | "mode" | "stages">): RunSettings;
103
+ export declare function runSettings(options: Pick<ReviewOptions, "limits" | "mode" | "stages" | "guidelineScope">): RunSettings;
101
104
  export declare function guidelinesShown(guidelines: string | undefined, settings: Pick<RunSettings, "without">): boolean;
@@ -1,4 +1,5 @@
1
1
  import { z } from "zod";
2
+ import { GUIDELINE_SCOPES } from "../docs/guidelines.js";
2
3
  import { OcraError } from "../errors.js";
3
4
  import { isOptionalContext, OPTIONAL_CONTEXT, } from "../review/context-sources.js";
4
5
  export const REVIEW_DEFAULTS = {
@@ -20,6 +21,10 @@ const limitsSchema = z.object({
20
21
  maxTasks: z.int().nonnegative().optional(),
21
22
  });
22
23
  export function runSettings(options) {
24
+ const guidelineScope = options.guidelineScope ?? "all";
25
+ if (!GUIDELINE_SCOPES.includes(guidelineScope)) {
26
+ throw new OcraError("CONFIG_INVALID", `ReviewOptions.guidelineScope must be one of ${GUIDELINE_SCOPES.join(", ")}`);
27
+ }
23
28
  const parsed = limitsSchema.safeParse(options.limits ?? {});
24
29
  if (!parsed.success) {
25
30
  throw new OcraError("CONFIG_INVALID", `ReviewOptions.limits is invalid: ${z.prettifyError(parsed.error)}`);
@@ -39,6 +44,7 @@ export function runSettings(options) {
39
44
  walkthrough: options.stages?.walkthrough === true,
40
45
  without: withoutContext(options.mode?.without ?? []),
41
46
  fixes: options.stages?.fixes === true,
47
+ guidelineScope,
42
48
  };
43
49
  }
44
50
  function withoutContext(names) {
@@ -1,5 +1,6 @@
1
1
  import { type Bundle } from "../bundle/bundle.js";
2
2
  import type { AgentRuntime, ReviewContext, Usage } from "../contracts.js";
3
+ import { type GuidelineSection } from "../docs/guidelines.js";
3
4
  import { type DocSection } from "../docs/project-docs.js";
4
5
  import type { ChangeRequest, FileDiff, PriorReview, RiskTier } from "../domain.js";
5
6
  import type { SelectLearnings } from "../knowledge/select.js";
@@ -24,6 +25,7 @@ export interface ReviewPlan {
24
25
  scope?: ReviewScope;
25
26
  context: ReviewContext;
26
27
  guidelines: string | undefined;
28
+ guidelineSections: GuidelineSection[];
27
29
  repoRules: SourcedRule[];
28
30
  memory: RememberedEntry[];
29
31
  learnings: SelectLearnings;
@@ -1,6 +1,7 @@
1
1
  import { roleCall } from "../agent/settings.js";
2
2
  import { bundleFiles, defaultBundlePolicy } from "../bundle/bundle.js";
3
3
  import { runtimeGrouper } from "../bundle/runtime-grouper.js";
4
+ import { guidelineSections } from "../docs/guidelines.js";
4
5
  import { docSections } from "../docs/project-docs.js";
5
6
  import { errorMessage } from "../errors.js";
6
7
  import { rank } from "../matrix/matrix.js";
@@ -94,6 +95,7 @@ export async function planReview(options, emit, signal) {
94
95
  : {}),
95
96
  context,
96
97
  guidelines,
98
+ guidelineSections: guidelines === undefined ? [] : guidelineSections(guidelines),
97
99
  repoRules: [
98
100
  ...(options.rules ?? []),
99
101
  ...fileRules.map((rule) => ({ ...rule, source: "repository" })),
@@ -27,6 +27,7 @@ export async function previewReview(options) {
27
27
  ultra: settings.ultra,
28
28
  securityFiles,
29
29
  without: settings.without,
30
+ guidelineScope: settings.guidelineScope,
30
31
  });
31
32
  const task = {
32
33
  taskId: cell.taskId,
@@ -1,3 +1,4 @@
1
+ import { type GuidelineScope } from "../docs/guidelines.js";
1
2
  import type { MatrixCell } from "../matrix/matrix.js";
2
3
  import type { OptionalContext } from "../review/context-sources.js";
3
4
  import { type ReviewPrompt, type ReviewPromptInput } from "../review/prompt.js";
@@ -14,6 +15,7 @@ export interface TaskPrompt {
14
15
  export interface TaskSettings {
15
16
  ultra: boolean;
16
17
  without?: ReadonlySet<OptionalContext>;
18
+ guidelineScope?: GuidelineScope;
17
19
  securityFiles: ReadonlySet<string>;
18
20
  }
19
- export declare function taskPrompt(cell: MatrixCell, plan: ReviewPlan, { ultra, securityFiles, without }: TaskSettings): TaskPrompt;
21
+ export declare function taskPrompt(cell: MatrixCell, plan: ReviewPlan, { ultra, securityFiles, without, guidelineScope }: TaskSettings): TaskPrompt;
@@ -1,3 +1,4 @@
1
+ import { guidelinesForTask } from "../docs/guidelines.js";
1
2
  import { sectionsFor } from "../docs/project-docs.js";
2
3
  import { memoryFor } from "../memory/memory.js";
3
4
  import { buildReviewPrompt } from "../review/prompt.js";
@@ -9,7 +10,7 @@ const PLAN_MIN_FILES = 5;
9
10
  const PLAN_MIN_PATCH_CHARS = 40_000;
10
11
  // What one task of the matrix sends: the run builds its prompt from this and
11
12
  // --plan previews it, so the preview cannot drift from the run.
12
- export function taskPrompt(cell, plan, { ultra, securityFiles, without }) {
13
+ export function taskPrompt(cell, plan, { ultra, securityFiles, without, guidelineScope = "all" }) {
13
14
  const files = cell.bundle.files.map((f) => f.newPath);
14
15
  const learnings = plan.learnings(cell.bundle.files);
15
16
  const docs = sectionsFor(plan.docSections, files);
@@ -21,7 +22,7 @@ export function taskPrompt(cell, plan, { ultra, securityFiles, without }) {
21
22
  bundle: cell.bundle.files,
22
23
  rules: resolveRules(files, [], cell.reviewer.rules),
23
24
  repoRules: resolveRules(files, plan.repoRules),
24
- guidelines: plan.guidelines,
25
+ ...guidelinesInput(guidelinesForTask(plan.guidelineSections, guidelineScope, files, cell.reviewer.scope?.requiresGuidelines === true)),
25
26
  ...(plan.linkedTasks && plan.linkedTasks.given.length > 0
26
27
  ? { linkedTasks: plan.linkedTasks.given }
27
28
  : {}),
@@ -46,6 +47,14 @@ export function taskPrompt(cell, plan, { ultra, securityFiles, without }) {
46
47
  },
47
48
  };
48
49
  }
50
+ function guidelinesInput(guidelines) {
51
+ if (!guidelines)
52
+ return {};
53
+ return {
54
+ guidelines: guidelines.text,
55
+ ...(guidelines.left.length > 0 ? { moreGuidelines: guidelines.left } : {}),
56
+ };
57
+ }
49
58
  function isLargeBundle({ files }) {
50
59
  const chars = files.reduce((sum, f) => sum + f.patch.length, 0);
51
60
  return files.length >= PLAN_MIN_FILES || chars >= PLAN_MIN_PATCH_CHARS;
@@ -14,6 +14,7 @@ export interface RuntimeOptions {
14
14
  sampling?: Sampling;
15
15
  }
16
16
  export interface CustomProvider {
17
+ api?: "openai" | "anthropic";
17
18
  baseUrl: string;
18
19
  apiKeyEnv?: string;
19
20
  models: Readonly<Record<string, ModelPrice>>;
@@ -8,7 +8,6 @@ import type { ContextSource, OptionalContext } from "./context-sources.js";
8
8
  import type { SymbolUse } from "./impact.js";
9
9
  import { type PromptText } from "./prompt-text.js";
10
10
  import type { ReviewerDefinition } from "./reviewer.js";
11
- export declare const MAX_GUIDELINES_CHARS = 20000;
12
11
  export interface ReviewPromptInput {
13
12
  reviewer: ReviewerDefinition;
14
13
  changeRequest: ChangeRequest;
@@ -17,6 +16,7 @@ export interface ReviewPromptInput {
17
16
  rules: string;
18
17
  repoRules?: string;
19
18
  guidelines?: string | undefined;
19
+ moreGuidelines?: readonly string[];
20
20
  linkedTasks?: readonly LinkedTask[];
21
21
  accepted?: readonly MemoryEntry[];
22
22
  learnings?: readonly Learning[];
@@ -1,8 +1,8 @@
1
+ import { MAX_GUIDELINES_CHARS } from "../docs/guidelines.js";
1
2
  import { PROJECT_DOC_LIMITS } from "../docs/project-docs.js";
2
3
  import { LINKED_TASK_LIMITS } from "../task/linked-task.js";
3
4
  import { data, join, ocraText, oneLine, section, truncated, } from "./prompt-text.js";
4
5
  import { REVIEW_TOOLS } from "./tools.js";
5
- export const MAX_GUIDELINES_CHARS = 20_000;
6
6
  // Runtimes cap an agent's turns, and on OpenCode the last turn has no tools:
7
7
  // a reviewer that kept its findings for the end lost them. A quarter of the
8
8
  // review tasks on Vertex ended at the cap (2026-09-28).
@@ -30,7 +30,7 @@ export function reviewPromptParts(input) {
30
30
  add("linked_tasks", renderLinkedTasks(input.linkedTasks));
31
31
  }
32
32
  if (input.guidelines?.trim() && !without.has("guidelines")) {
33
- add("guidelines", section("repository_guidelines", truncated(input.guidelines, MAX_GUIDELINES_CHARS)));
33
+ add("guidelines", renderGuidelines(input.guidelines, input.moreGuidelines ?? []));
34
34
  }
35
35
  const rules = renderRules(input.rules, without.has("rules") ? "" : (input.repoRules ?? ""));
36
36
  if (rules)
@@ -74,6 +74,24 @@ export function renderChangeRequest(cr, maxDescription = MAX_DESCRIPTION_CHARS,
74
74
  ...(withDescription ? [section("description", truncated(cr.description, maxDescription))] : []),
75
75
  ]);
76
76
  }
77
+ const MAX_LISTED_GUIDELINES = 30;
78
+ // Sections are chosen whole (docs/guidelines.ts); the cut here only bounds
79
+ // a document whose first section alone is over the limit.
80
+ function renderGuidelines(text, left) {
81
+ const listed = left.slice(0, MAX_LISTED_GUIDELINES);
82
+ return section("repository_guidelines", [
83
+ truncated(text, MAX_GUIDELINES_CHARS),
84
+ ...(listed.length > 0
85
+ ? [
86
+ ocraText(`More sections of AGENTS.md, by heading; read it with ${REVIEW_TOOLS.readFile} if one may apply:`),
87
+ ...listed.map((h) => data(`- ${oneLine(clip(h, MAX_TITLE_CHARS))}`)),
88
+ ...(left.length > listed.length
89
+ ? [ocraText(`and ${left.length - listed.length} more.`)]
90
+ : []),
91
+ ]
92
+ : []),
93
+ ]);
94
+ }
77
95
  // The reviewer's rules are ocra's and short; the repository's are held to a
78
96
  // limit, as the guidelines are.
79
97
  function renderRules(builtin, repo) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-cr-agent/core",
3
- "version": "0.12.0",
3
+ "version": "0.14.0",
4
4
  "description": "Domain types, review pipeline stages and plugin contracts for Open-CR-Agent",
5
5
  "keywords": [
6
6
  "code-review",