@open-cr-agent/core 0.17.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +1 -1
  2. package/dist/agent/pool.d.ts +1 -0
  3. package/dist/agent/pool.js +21 -0
  4. package/dist/contracts.d.ts +1 -0
  5. package/dist/generate/targets.d.ts +1 -0
  6. package/dist/generate/targets.js +1 -1
  7. package/dist/index.d.ts +3 -0
  8. package/dist/index.js +3 -0
  9. package/dist/internal.d.ts +4 -1
  10. package/dist/internal.js +4 -1
  11. package/dist/judge/judge.d.ts +3 -1
  12. package/dist/judge/judge.js +8 -8
  13. package/dist/mend/gate.d.ts +11 -0
  14. package/dist/mend/gate.js +128 -0
  15. package/dist/mend/patch.d.ts +31 -0
  16. package/dist/mend/patch.js +50 -0
  17. package/dist/mend/state.d.ts +23 -0
  18. package/dist/mend/state.js +23 -0
  19. package/dist/mend/verify.d.ts +18 -0
  20. package/dist/mend/verify.js +76 -0
  21. package/dist/net/fetch-failure.d.ts +1 -0
  22. package/dist/net/fetch-failure.js +20 -0
  23. package/dist/pipeline/assemble-report.js +4 -0
  24. package/dist/pipeline/check-stage.d.ts +3 -2
  25. package/dist/pipeline/check-stage.js +12 -15
  26. package/dist/pipeline/early-check.d.ts +16 -0
  27. package/dist/pipeline/early-check.js +95 -0
  28. package/dist/pipeline/execute-stage.d.ts +4 -0
  29. package/dist/pipeline/execute-stage.js +21 -1
  30. package/dist/pipeline/filter-stage.js +1 -1
  31. package/dist/pipeline/findings.d.ts +1 -1
  32. package/dist/pipeline/findings.js +7 -3
  33. package/dist/pipeline/fix-finding.d.ts +59 -0
  34. package/dist/pipeline/fix-finding.js +123 -0
  35. package/dist/pipeline/mend.d.ts +43 -0
  36. package/dist/pipeline/mend.js +262 -0
  37. package/dist/pipeline/options.d.ts +2 -0
  38. package/dist/pipeline/plan.js +6 -3
  39. package/dist/pipeline/run.js +3 -2
  40. package/dist/pipeline/task-prompt.js +7 -1
  41. package/dist/pipeline/task.js +7 -0
  42. package/dist/plugin/types.d.ts +1 -0
  43. package/dist/report/inline.d.ts +37 -0
  44. package/dist/report/inline.js +67 -0
  45. package/dist/report/output-schema.d.ts +15 -0
  46. package/dist/report/output-schema.js +2 -0
  47. package/dist/report/output.js +7 -0
  48. package/dist/report/report.d.ts +8 -0
  49. package/dist/rereview/reconcile.d.ts +1 -0
  50. package/dist/rereview/reconcile.js +5 -1
  51. package/dist/review/prompt-text.d.ts +1 -1
  52. package/dist/review/prompt-text.js +3 -0
  53. package/dist/review/reviewers/agents-md.js +4 -1
  54. package/dist/review/reviewers/correctness.js +5 -2
  55. package/dist/review/reviewers/docs.js +5 -2
  56. package/dist/review/reviewers/performance.js +5 -2
  57. package/dist/review/reviewers/security.js +5 -2
  58. package/dist/review/reviewers/writing.d.ts +1 -0
  59. package/dist/review/reviewers/writing.js +8 -0
  60. package/dist/rules/repo-rules.d.ts +3 -0
  61. package/dist/rules/repo-rules.js +19 -0
  62. package/dist/runtime/attempt.d.ts +1 -0
  63. package/dist/runtime/attempt.js +4 -1
  64. package/dist/runtime/failback.js +3 -2
  65. package/dist/runtime/text-tools.d.ts +16 -0
  66. package/dist/runtime/text-tools.js +60 -0
  67. package/dist/runtime/tools.js +5 -1
  68. package/dist/verify/early.d.ts +22 -0
  69. package/dist/verify/early.js +79 -0
  70. package/dist/verify/verify.d.ts +13 -0
  71. package/dist/verify/verify.js +77 -64
  72. package/package.json +3 -3
@@ -0,0 +1,262 @@
1
+ import { oneShot } from "../agent/model-call.js";
2
+ import { mapWithConcurrency } from "../agent/pool.js";
3
+ import { roleCall } from "../agent/settings.js";
4
+ import { spendLimit } from "../agent/spend-limit.js";
5
+ import { OcraError } from "../errors.js";
6
+ import { FIX_REJECTIONS } from "../fix/check.js";
7
+ import { headMode } from "../generate/targets.js";
8
+ import { GATE_REJECTIONS, gate, mendScope } from "../mend/gate.js";
9
+ import { composePatches } from "../mend/patch.js";
10
+ import { closedAs, EMPTY_STATE, MEND_LIMITS, roundStop, } from "../mend/state.js";
11
+ import { VERIFICATION_REJECTIONS, verifierStep } from "../mend/verify.js";
12
+ import { oneLine } from "../review/prompt-text.js";
13
+ import { reviewContext } from "./context.js";
14
+ import { fixAtHead } from "./fix-finding.js";
15
+ const CONCURRENCY = 3;
16
+ const SUBJECT_TITLE_CHARS = 100;
17
+ // `propose` ends a round with its checked changes for a person to commit;
18
+ // `commit` writes them to the change request's branch.
19
+ export const MEND_LEVELS = ["propose", "commit"];
20
+ // fixed, proposed: its patch is in the round's commit, or in what the round
21
+ // proposes. rejected: this round wrote no patch that passed; another may.
22
+ // deferred: not tried, or tried and not written; no attempt is counted.
23
+ // needs_human, gone: closed, for a person or because its code is gone.
24
+ export const MEND_ITEM_OUTCOMES = [
25
+ "fixed",
26
+ "proposed",
27
+ "rejected",
28
+ "deferred",
29
+ "needs_human",
30
+ "gone",
31
+ ];
32
+ export const MEND_ITEM_REASONS = [
33
+ ...new Set([
34
+ ...FIX_REJECTIONS,
35
+ "not_candidate",
36
+ ...GATE_REJECTIONS,
37
+ ...VERIFICATION_REJECTIONS,
38
+ "overlap",
39
+ "no_room",
40
+ "attempts",
41
+ "head_moved",
42
+ "not_writable",
43
+ ]),
44
+ ];
45
+ export const MEND_OUTCOMES = [
46
+ "committed",
47
+ "proposed",
48
+ "nothing",
49
+ "stopped",
50
+ "head_moved",
51
+ "not_writable",
52
+ ];
53
+ // A person decides these: no later round at this head answers differently.
54
+ const FOR_A_PERSON = new Set([
55
+ "not_candidate",
56
+ "no_parser",
57
+ "out_of_scope",
58
+ "protected",
59
+ "too_large",
60
+ "tamper",
61
+ ]);
62
+ // One round of the fix loop (ADR-0078) over accepted findings: each open
63
+ // finding gets a patch from the fix stage's checked completion, the gate and
64
+ // the verifier decide what is kept, and the kept patches become one commit
65
+ // from the head they were made at. Nothing from the change runs.
66
+ export async function mendRound(options) {
67
+ const { vcs } = options;
68
+ const before = options.state ?? EMPTY_STATE;
69
+ const warnings = [];
70
+ if (!oneShot(options.runtime, () => { })) {
71
+ throw new OcraError("RUNTIME_START_FAILED", `the ${options.runtime.name} runtime makes no plain completions, which ocra mend needs`);
72
+ }
73
+ const { headSha } = await vcs.getChangeRequest();
74
+ const ended = (round) => ({
75
+ headSha,
76
+ items: [],
77
+ state: before,
78
+ warnings,
79
+ ...round,
80
+ });
81
+ if (options.expectedHead !== undefined && options.expectedHead !== headSha) {
82
+ return ended({ outcome: "head_moved" });
83
+ }
84
+ if (options.level === "commit" && !vcs.commit)
85
+ return ended({ outcome: "not_writable" });
86
+ const stopped = roundStop(before, options.maxCostUsd);
87
+ if (stopped)
88
+ return ended({ outcome: "stopped", stopped });
89
+ const findings = unique(options.findings);
90
+ const results = new Map();
91
+ const open = [];
92
+ for (const finding of findings) {
93
+ const id = finding.fingerprint;
94
+ const closed = closedAs(before.items[id]);
95
+ if (closed) {
96
+ const used = before.items[id]?.closed === undefined;
97
+ results.set(id, { id, outcome: closed, ...(used ? { reason: "attempts" } : {}) });
98
+ }
99
+ else if (open.length < MEND_LIMITS.itemsPerRound)
100
+ open.push(finding);
101
+ else
102
+ results.set(id, { id, outcome: "deferred", reason: "no_room" });
103
+ }
104
+ const listed = () => findings.map((f) => results.get(f.fingerprint));
105
+ if (open.length === 0)
106
+ return ended({ outcome: "nothing", items: listed() });
107
+ const diffs = await vcs.getDiff();
108
+ const head = {
109
+ diffs,
110
+ context: reviewContext(vcs, diffs),
111
+ scope: mendScope(diffs, options.protectedPaths),
112
+ contents: new Map(),
113
+ };
114
+ const remaining = options.maxCostUsd === undefined ? undefined : options.maxCostUsd - before.costUsd;
115
+ const limit = spendLimit(remaining);
116
+ let spent = 0;
117
+ const onUsage = (usage) => {
118
+ spent += usage.costUsd;
119
+ options.onUsage(usage);
120
+ };
121
+ // The fixer's calls are charged to the limit where they are made.
122
+ const ask = oneShot(options.runtime, (usage) => {
123
+ limit.charge(usage);
124
+ onUsage(usage);
125
+ });
126
+ const steps = [
127
+ verifierStep(ask, roleCall("verifier", options), (w) => warnings.push(w)),
128
+ ];
129
+ const attempts = await mapWithConcurrency(open, CONCURRENCY, async (finding) => {
130
+ if (!limit.mayCall())
131
+ return { outcome: "deferred", reason: "no_room" };
132
+ return attempt(finding, head, steps, {
133
+ runtime: options.runtime,
134
+ syntax: options.syntax,
135
+ spendLimit: limit,
136
+ call: roleCall("fixer", options),
137
+ signal: options.signal,
138
+ onUsage,
139
+ onWarning: (w) => warnings.push(w),
140
+ });
141
+ });
142
+ const patches = [];
143
+ open.forEach((finding, i) => {
144
+ const tried = attempts[i];
145
+ if ("patch" in tried)
146
+ patches.push(tried.patch);
147
+ else
148
+ results.set(finding.fingerprint, { id: finding.fingerprint, ...tried });
149
+ });
150
+ const composed = composePatches(patches, head.contents, MEND_LIMITS);
151
+ for (const { item, reason } of composed.left) {
152
+ results.set(item, { id: item, outcome: "deferred", reason });
153
+ }
154
+ let round = { outcome: "nothing" };
155
+ if (composed.changes.length > 0) {
156
+ round =
157
+ options.level === "propose"
158
+ ? { outcome: "proposed" }
159
+ : await commit(vcs, headSha, composed.changes, kept(findings, composed.kept), diffs);
160
+ }
161
+ for (const patch of patches.filter((p) => composed.kept.includes(p.item))) {
162
+ const id = patch.item;
163
+ results.set(id, round.outcome === "committed"
164
+ ? { id, outcome: "fixed", edits: patch.hunks }
165
+ : round.outcome === "proposed"
166
+ ? { id, outcome: "proposed", edits: patch.hunks }
167
+ : { id, outcome: "deferred", reason: round.outcome });
168
+ }
169
+ return ended({ ...round, items: listed(), state: nextState(before, results, spent) });
170
+ }
171
+ // One finding through its lane, the gate and the verification steps.
172
+ async function attempt(finding, head, steps, deps) {
173
+ const refuse = (reason) => ({
174
+ outcome: reason === "stale" ? "gone" : FOR_A_PERSON.has(reason) ? "needs_human" : "rejected",
175
+ reason,
176
+ });
177
+ const outside = head.scope.refusal(finding.file);
178
+ if (outside)
179
+ return refuse(outside);
180
+ const fixed = await fixAtHead(finding, { ...deps, diffs: head.diffs, context: head.context });
181
+ for (const warning of fixed.warnings)
182
+ deps.onWarning(warning);
183
+ if (!("fix" in fixed))
184
+ return refuse(fixed.reason);
185
+ const content = await head.context.readFile(finding.file);
186
+ if (content === undefined)
187
+ return refuse("stale");
188
+ head.contents.set(finding.file, content);
189
+ const patch = {
190
+ item: finding.fingerprint,
191
+ hunks: [{ path: finding.file, ...fixed.fix }],
192
+ };
193
+ const gated = await gate(patch, head.contents, head.scope, deps.syntax, MEND_LIMITS);
194
+ if (gated)
195
+ return refuse(gated);
196
+ for (const step of steps) {
197
+ if (!deps.spendLimit.mayCall())
198
+ return { outcome: "deferred", reason: "no_room" };
199
+ const refused = await step({ title: finding.title, body: finding.body, patch, heads: head.contents }, deps.signal);
200
+ if (refused)
201
+ return refuse(refused);
202
+ }
203
+ return { patch };
204
+ }
205
+ async function commit(vcs, parent, changes, fixed, diffs) {
206
+ if (!vcs.commit)
207
+ return { outcome: "not_writable" };
208
+ const change = {
209
+ parent,
210
+ message: commitMessage(fixed),
211
+ files: changes.map(({ path, after }) => ({
212
+ path,
213
+ content: after,
214
+ created: false,
215
+ executable: executable(path, diffs),
216
+ })),
217
+ };
218
+ const result = await vcs.commit(change);
219
+ return result.committed ? { outcome: "committed", sha: result.sha } : { outcome: result.outcome };
220
+ }
221
+ function executable(path, diffs) {
222
+ const diff = diffs.find((d) => d.newPath === path);
223
+ return diff !== undefined && headMode(diff) === "100755";
224
+ }
225
+ // Titles and paths come from a review of the change: one line each, cut, and
226
+ // behind a list marker, so none can add a trailer or a line of its own.
227
+ function commitMessage(fixed) {
228
+ const clean = (text) => oneLine(text).replace(/[\p{Cc}\p{Cf}\u2028\u2029]+/gu, " ");
229
+ return [
230
+ `fix: apply ocra's fixes for ${fixed.length} finding${fixed.length === 1 ? "" : "s"}`,
231
+ "",
232
+ ...fixed.map((f) => `- ${clean(f.file)}: ${clean(f.title).slice(0, SUBJECT_TITLE_CHARS)}`),
233
+ "",
234
+ "ocra ran nothing from the repository to check these edits: the change request's own checks do.",
235
+ ].join("\n");
236
+ }
237
+ function kept(findings, ids) {
238
+ return findings.filter((f) => ids.includes(f.fingerprint));
239
+ }
240
+ function unique(findings) {
241
+ const seen = new Set();
242
+ return findings.filter((f) => !seen.has(f.fingerprint) && seen.add(f.fingerprint));
243
+ }
244
+ // A deferred item was not tried, or its patch was not written: its attempt
245
+ // is not counted, so a person's push or a full round costs it nothing.
246
+ function nextState(before, results, spent) {
247
+ const items = { ...before.items };
248
+ for (const { id, outcome } of results.values()) {
249
+ const was = items[id] ?? { attempts: 0 };
250
+ if (outcome === "deferred" || was.closed)
251
+ continue;
252
+ const used = closedAs(was);
253
+ if (used)
254
+ items[id] = { ...was, closed: used };
255
+ else if (outcome === "needs_human" || outcome === "gone") {
256
+ items[id] = { attempts: was.attempts + 1, closed: outcome };
257
+ }
258
+ else
259
+ items[id] = { attempts: was.attempts + 1 };
260
+ }
261
+ return { rounds: before.rounds + 1, costUsd: before.costUsd + spent, items };
262
+ }
@@ -8,6 +8,7 @@ import type { ProjectDoc } from "../docs/project-docs.js";
8
8
  import type { Learning } from "../knowledge/learning.js";
9
9
  import type { MemoryEntry } from "../memory/memory.js";
10
10
  import type { MergeCheck } from "../merge-checks/merge-check.js";
11
+ import type { InlinePolicy } from "../report/inline.js";
11
12
  import type { ReviewEvent } from "../report/report.js";
12
13
  import { type OptionalContext } from "../review/context-sources.js";
13
14
  import type { ReviewerDefinition } from "../review/reviewer.js";
@@ -37,6 +38,7 @@ export interface ReviewOptions {
37
38
  mergeChecks?: readonly MergeCheck[];
38
39
  selection?: Partial<SelectionPolicy>;
39
40
  limits?: ReviewLimits;
41
+ inline?: InlinePolicy;
40
42
  stages?: ReviewStages;
41
43
  mode?: ReviewMode;
42
44
  identity?: RunIdentity;
@@ -6,7 +6,7 @@ import { docSections } from "../docs/project-docs.js";
6
6
  import { errorMessage } from "../errors.js";
7
7
  import { rank } from "../matrix/matrix.js";
8
8
  import { MEMORY_PATH, mergeMemory, parseMemory } from "../memory/memory.js";
9
- import { parseRepoRules, REPO_RULES_PATH, } from "../rules/repo-rules.js";
9
+ import { MARKDOWN_RULES_PATH, parseMarkdownRules, parseRepoRules, REPO_RULES_PATH, } from "../rules/repo-rules.js";
10
10
  import { analyzerEvidence } from "../sarif/evidence.js";
11
11
  import { binaryTextWarning, defaultSelectionPolicy, selectFiles, } from "../select/select.js";
12
12
  import { triage } from "../triage.js";
@@ -115,8 +115,11 @@ export async function planReview(options, emit, signal) {
115
115
  };
116
116
  }
117
117
  async function loadRepoRules(read) {
118
- const text = await read(REPO_RULES_PATH);
119
- return text === undefined ? [] : parseRepoRules(text);
118
+ const [json, markdown] = await Promise.all([read(REPO_RULES_PATH), read(MARKDOWN_RULES_PATH)]);
119
+ return [
120
+ ...(json === undefined ? [] : parseRepoRules(json)),
121
+ ...(markdown === undefined ? [] : parseMarkdownRules(markdown)),
122
+ ];
120
123
  }
121
124
  // Review only what changed since the prior review when the platform can
122
125
  // tell; otherwise everything, with the reason in the report.
@@ -13,7 +13,8 @@ import { newRunId } from "./run-id.js";
13
13
  import { walkthroughStage } from "./walkthrough-stage.js";
14
14
  // The library entry: plan (deterministic stages) → execute (one agent task
15
15
  // per cell, beside the walkthrough and the pre-merge checks) → filter
16
- // (memory, the previous review) → check (verify, judge) → fix → report. The `ocra`
16
+ // (memory, the previous review) → check (verify, which starts while tasks
17
+ // still run, and judge) → fix → report. The `ocra`
17
18
  // command is one caller. The manual's Embedding page says which options are
18
19
  // a contract.
19
20
  export function review(options) {
@@ -43,7 +44,7 @@ export async function reviewWithHooks(options) {
43
44
  const mergeChecks = mergeChecksStage(context);
44
45
  const executed = await executeStage(reviewers, context);
45
46
  const filtered = await filterStage(executed, plan.prior.review, context);
46
- const checked = await checkStage(filtered, context);
47
+ const checked = await checkStage(filtered, executed.early, context);
47
48
  const fixed = await fixStage(checked, context);
48
49
  const report = assembleReport({ runId, reviewers }, {
49
50
  executed,
@@ -35,7 +35,7 @@ export function taskPrompt(cell, plan, { ultra, securityFiles, without, guidelin
35
35
  };
36
36
  const prompt = buildReviewPrompt(input);
37
37
  const callers = (ultra || plan.tier === "full") && !without?.has("callers");
38
- if (!ultra && !isLargeBundle(cell.bundle))
38
+ if (!ultra && !plansFirst(cell))
39
39
  return { input, prompt, callers };
40
40
  return {
41
41
  input,
@@ -55,6 +55,12 @@ function guidelinesInput(guidelines) {
55
55
  ...(guidelines.left.length > 0 ? { moreGuidelines: guidelines.left } : {}),
56
56
  };
57
57
  }
58
+ // A checklist orders a reviewer's steps inside one large bundle. A reviewer
59
+ // that takes the change as a whole is over the size on most changes, and
60
+ // its plan calls were a tenth of a review's bill for no finding more.
61
+ function plansFirst({ reviewer, bundle }) {
62
+ return (reviewer.scope?.span ?? "bundle") === "bundle" && isLargeBundle(bundle);
63
+ }
58
64
  function isLargeBundle({ files }) {
59
65
  const chars = files.reduce((sum, f) => sum + f.patch.length, 0);
60
66
  return files.length >= PLAN_MIN_FILES || chars >= PLAN_MIN_PATCH_CHARS;
@@ -2,6 +2,7 @@ import { SpendLimitReached } from "../agent/spend-limit.js";
2
2
  import { addUsage, emptyUsage } from "../agent/usage.js";
3
3
  import { reportedFindingSchema } from "../domain.js";
4
4
  import { errorMessage } from "../errors.js";
5
+ import { oneLine } from "../review/prompt-text.js";
5
6
  export async function executeTask(runtime, spec, runSignal, callbacks) {
6
7
  const timeout = AbortSignal.timeout(spec.timeoutMs);
7
8
  const signal = AbortSignal.any([runSignal, timeout]);
@@ -116,6 +117,12 @@ function handle(event, result, callbacks) {
116
117
  result.ended = event.ended;
117
118
  if (event.wrapUp)
118
119
  result.wrapUp = { findings: event.wrapUp.findings };
120
+ if (event.refusedFindings?.length) {
121
+ result.warnings.push(`${event.refusedFindings.length} finding(s) the reviewer reported were refused for their arguments and are missing (${event.refusedFindings
122
+ .slice(0, MAX_FINDINGS_PER_TASK)
123
+ .map((fields) => oneLine(fields).slice(0, 100))
124
+ .join("; ")})`);
125
+ }
119
126
  return true;
120
127
  case "error":
121
128
  result.status = "failed";
@@ -19,6 +19,7 @@ export interface CustomProvider {
19
19
  apiKeyEnv?: string;
20
20
  models: Readonly<Record<string, ModelPrice>>;
21
21
  effort?: "openai" | "openrouter";
22
+ toolCalls?: "api" | "text";
22
23
  }
23
24
  export interface ModelPrice {
24
25
  input: number;
@@ -0,0 +1,37 @@
1
+ import { z } from "zod";
2
+ import { type Finding, type Severity } from "../domain.js";
3
+ export declare const INLINE_HOLD_REASONS: readonly ["below_floor", "over_cap"];
4
+ export type InlineHoldReason = (typeof INLINE_HOLD_REASONS)[number];
5
+ export interface InlinePolicy {
6
+ minSeverity?: Severity;
7
+ maxComments?: number;
8
+ }
9
+ export interface InlineSelection extends InlinePolicy {
10
+ held: {
11
+ fingerprint: string;
12
+ reason: InlineHoldReason;
13
+ }[];
14
+ }
15
+ export declare const inlineSelectionSchema: z.ZodObject<{
16
+ minSeverity: z.ZodExactOptional<z.ZodEnum<{
17
+ critical: "critical";
18
+ suggestion: "suggestion";
19
+ warning: "warning";
20
+ }>>;
21
+ maxComments: z.ZodExactOptional<z.ZodInt>;
22
+ held: z.ZodArray<z.ZodObject<{
23
+ fingerprint: z.ZodString;
24
+ reason: z.ZodEnum<{
25
+ below_floor: "below_floor";
26
+ over_cap: "over_cap";
27
+ }>;
28
+ }, z.core.$strict>>;
29
+ }, z.core.$strict>;
30
+ /**
31
+ * The findings a policy holds back from inline comments: those below its
32
+ * floor, then those past its cap among the rest when ranked. The cap counts
33
+ * this review's findings, so one commented on in an earlier review and
34
+ * reported again takes a place without being posted twice. Undefined
35
+ * without a policy.
36
+ */
37
+ export declare function selectInline(findings: readonly Finding[], policy: InlinePolicy): InlineSelection | undefined;
@@ -0,0 +1,67 @@
1
+ import { z } from "zod";
2
+ import { severitySchema } from "../domain.js";
3
+ // Which findings a platform may post as inline comments (ADR-0076). A
4
+ // policy never removes a finding from the report or changes the verdict: a
5
+ // finding it holds back is listed in the summary instead.
6
+ export const INLINE_HOLD_REASONS = ["below_floor", "over_cap"];
7
+ export const inlineSelectionSchema = z.strictObject({
8
+ minSeverity: severitySchema.exactOptional(),
9
+ maxComments: z.int().nonnegative().exactOptional(),
10
+ held: z.array(z.strictObject({ fingerprint: z.string(), reason: z.enum(INLINE_HOLD_REASONS) })),
11
+ });
12
+ const SEVERITY_RANK = { critical: 0, warning: 1, suggestion: 2 };
13
+ const VERIFICATION_RANK = {
14
+ confirmed: 0,
15
+ uncertain: 1,
16
+ unchecked: 2,
17
+ };
18
+ // More severe first, then what Verify confirmed, then what the judge did not
19
+ // mark low confidence, then by place and fingerprint, so the order does not
20
+ // depend on the order tasks ended in.
21
+ function compareForInline(a, b) {
22
+ return (SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity] ||
23
+ VERIFICATION_RANK[a.verification ?? "unchecked"] -
24
+ VERIFICATION_RANK[b.verification ?? "unchecked"] ||
25
+ Number(a.lowConfidence === true) - Number(b.lowConfidence === true) ||
26
+ compareText(a.file, b.file) ||
27
+ (a.lineRange?.start ?? 0) - (b.lineRange?.start ?? 0) ||
28
+ compareText(a.fingerprint, b.fingerprint));
29
+ }
30
+ function compareText(a, b) {
31
+ return a < b ? -1 : a > b ? 1 : 0;
32
+ }
33
+ /** A finding a platform can comment on inline: anchored to lines in the diff. */
34
+ function postableInline(f) {
35
+ return f.lineRange !== undefined && f.anchor.inDiff;
36
+ }
37
+ /**
38
+ * The findings a policy holds back from inline comments: those below its
39
+ * floor, then those past its cap among the rest when ranked. The cap counts
40
+ * this review's findings, so one commented on in an earlier review and
41
+ * reported again takes a place without being posted twice. Undefined
42
+ * without a policy.
43
+ */
44
+ export function selectInline(findings, policy) {
45
+ const { minSeverity, maxComments } = policy;
46
+ if (minSeverity === undefined && maxComments === undefined)
47
+ return undefined;
48
+ const ranked = findings.filter(postableInline).sort(compareForInline);
49
+ const held = [];
50
+ let kept = 0;
51
+ for (const f of ranked) {
52
+ if (minSeverity !== undefined && SEVERITY_RANK[f.severity] > SEVERITY_RANK[minSeverity]) {
53
+ held.push({ fingerprint: f.fingerprint, reason: "below_floor" });
54
+ }
55
+ else if (maxComments !== undefined && kept >= maxComments) {
56
+ held.push({ fingerprint: f.fingerprint, reason: "over_cap" });
57
+ }
58
+ else {
59
+ kept += 1;
60
+ }
61
+ }
62
+ return {
63
+ ...(minSeverity !== undefined ? { minSeverity } : {}),
64
+ ...(maxComments !== undefined ? { maxComments } : {}),
65
+ held,
66
+ };
67
+ }
@@ -432,6 +432,21 @@ export declare const reportOutputSchema: z.ZodObject<{
432
432
  total: "total";
433
433
  }>>;
434
434
  }, z.core.$strict>>;
435
+ inline: z.ZodExactOptional<z.ZodObject<{
436
+ minSeverity: z.ZodExactOptional<z.ZodEnum<{
437
+ critical: "critical";
438
+ suggestion: "suggestion";
439
+ warning: "warning";
440
+ }>>;
441
+ maxComments: z.ZodExactOptional<z.ZodInt>;
442
+ held: z.ZodArray<z.ZodObject<{
443
+ fingerprint: z.ZodString;
444
+ reason: z.ZodEnum<{
445
+ below_floor: "below_floor";
446
+ over_cap: "over_cap";
447
+ }>;
448
+ }, z.core.$strict>>;
449
+ }, z.core.$strict>>;
435
450
  provenance: z.ZodExactOptional<z.ZodObject<{
436
451
  ocraVersion: z.ZodString;
437
452
  promptHash: z.ZodString;
@@ -8,6 +8,7 @@ import { memoryEntrySchema } from "../memory/memory.js";
8
8
  import { MERGE_CHECK_OUTCOMES } from "../merge-checks/merge-check.js";
9
9
  import { exclusionReasonSchema } from "../select/select.js";
10
10
  import { TASK_TRACKERS } from "../task/linked-task.js";
11
+ import { inlineSelectionSchema } from "./inline.js";
11
12
  import { taskStatusSchema } from "./report.js";
12
13
  // The published shape of a review: `--format json` and a session's
13
14
  // report.json. It is a contract with scripts and CI, so it carries a version
@@ -255,6 +256,7 @@ export const reportOutputSchema = z.strictObject({
255
256
  spendLimit: z
256
257
  .strictObject({ usd: z.number(), reached: z.enum(["review", "total"]).exactOptional() })
257
258
  .exactOptional(),
259
+ inline: inlineSelectionSchema.exactOptional(),
258
260
  provenance: provenanceSchema.exactOptional(),
259
261
  usage: usageSchema,
260
262
  warnings: z.array(z.string()),
@@ -60,6 +60,13 @@ export function toReportOutput(report) {
60
60
  output.anchoring = outputAnchoring(report.anchoring);
61
61
  if (report.spendLimit)
62
62
  output.spendLimit = outputSpendLimit(report.spendLimit);
63
+ if (report.inline) {
64
+ const { held, ...policy } = report.inline;
65
+ output.inline = {
66
+ ...policy,
67
+ held: held.map(({ fingerprint, reason }) => ({ fingerprint, reason })),
68
+ };
69
+ }
63
70
  if (report.provenance)
64
71
  output.provenance = outputProvenance(report.provenance);
65
72
  if (report.rereview) {
@@ -13,6 +13,7 @@ import type { ExclusionReason } from "../select/select.js";
13
13
  import type { LinkedTaskUse } from "../task/linked-task.js";
14
14
  import type { RefutedFinding } from "../verify/verify.js";
15
15
  import type { Walkthrough } from "../walkthrough/walkthrough.js";
16
+ import type { InlineSelection } from "./inline.js";
16
17
  import type { RunProvenance } from "./provenance.js";
17
18
  export type CoverageEntry = {
18
19
  path: string;
@@ -117,6 +118,7 @@ export interface ReviewReport {
117
118
  usd: number;
118
119
  reached?: "review" | "total";
119
120
  };
121
+ inline?: InlineSelection;
120
122
  provenance?: RunProvenance;
121
123
  usage: Usage;
122
124
  warnings: string[];
@@ -183,6 +185,12 @@ export type ReviewEvent = {
183
185
  } | {
184
186
  type: "usage_reported";
185
187
  usage: Usage;
188
+ } | {
189
+ type: "findings_verified";
190
+ file: string;
191
+ kept: Finding[];
192
+ refuted: string[];
193
+ settled: string[];
186
194
  } | {
187
195
  type: "verification_finished";
188
196
  checked: number;
@@ -16,4 +16,5 @@ export interface Reconciled {
16
16
  dismissed: PriorFinding[];
17
17
  }
18
18
  export declare function reconcile(input: ReconcileInput): Reconciled;
19
+ export declare function staysDismissed(finding: Pick<Finding, "severity">, old: PriorFinding): boolean;
19
20
  export declare function stillOpen(reconciled: Reconciled): PriorFinding[];
@@ -32,7 +32,7 @@ export function reconcile(input) {
32
32
  }
33
33
  for (const finding of findings) {
34
34
  const old = before.get(finding.fingerprint);
35
- if (old?.dismissed && RANK[finding.severity] <= RANK[old.severity]) {
35
+ if (old && staysDismissed(finding, old)) {
36
36
  result.dismissed.push(old);
37
37
  continue;
38
38
  }
@@ -44,6 +44,10 @@ export function reconcile(input) {
44
44
  }
45
45
  return result;
46
46
  }
47
+ // A person's dismissal holds unless the finding came back more severe.
48
+ export function staysDismissed(finding, old) {
49
+ return !!old.dismissed && RANK[finding.severity] <= RANK[old.severity];
50
+ }
47
51
  // Earlier findings that are neither fixed nor dismissed keep counting towards
48
52
  // the verdict, so the same code reviewed twice cannot flip it by chance.
49
53
  export function stillOpen(reconciled) {
@@ -2,7 +2,7 @@ declare const brand: unique symbol;
2
2
  export type PromptText = string & {
3
3
  readonly [brand]: "PromptText";
4
4
  };
5
- declare const SECTIONS: readonly ["change_request", "title", "description", "changed_files", "linked_tasks", "task", "body", "parent", "subtasks", "project_docs", "doc", "doc_index", "repository_guidelines", "review_rules", "accepted_findings", "team_learnings", "learning", "learning_index", "review_files", "file", "findings", "finding", "lines_to_replace", "diff", "file_excerpt", "related_code", "callers", "analyzer_results", "review_plan", "reply", "thread", "question", "merge_checks", "check"];
5
+ declare const SECTIONS: readonly ["change_request", "title", "description", "changed_files", "linked_tasks", "task", "body", "parent", "subtasks", "project_docs", "doc", "doc_index", "repository_guidelines", "review_rules", "accepted_findings", "team_learnings", "learning", "learning_index", "review_files", "file", "findings", "finding", "lines_to_replace", "replacement", "edit", "diff", "file_excerpt", "related_code", "callers", "analyzer_results", "review_plan", "reply", "thread", "question", "merge_checks", "check", "tool_result"];
6
6
  export type SectionName = (typeof SECTIONS)[number];
7
7
  export declare function data(text: string): PromptText;
8
8
  export declare function ocraText(text: string): PromptText;
@@ -37,6 +37,8 @@ const SECTIONS = [
37
37
  "findings",
38
38
  "finding",
39
39
  "lines_to_replace",
40
+ "replacement",
41
+ "edit",
40
42
  "diff",
41
43
  "file_excerpt",
42
44
  "related_code",
@@ -48,6 +50,7 @@ const SECTIONS = [
48
50
  "question",
49
51
  "merge_checks",
50
52
  "check",
53
+ "tool_result",
51
54
  ];
52
55
  // Characters a tokenizer may drop or a model may read past: whitespace,
53
56
  // every default-ignorable code point (joiners, direction marks, variation
@@ -1,5 +1,6 @@
1
1
  import { REVIEW_TOOLS as T } from "../tools.js";
2
2
  import { TEST_FILES } from "./scopes.js";
3
+ import { FINDING_WRITING } from "./writing.js";
3
4
  // Each reviewer's prompt is written and measured on its own; shared wording
4
5
  // would tie one reviewer's evaluation to another's edits.
5
6
  const SYSTEM_PROMPT = `You are the AGENTS.md reviewer in a multi-agent code review system. You review one bundle of changed files in a pull request and report where this change makes the repository's agent guidelines out of date. The guidelines are shown in <ocra_repository_guidelines>; other reviewers check that the code follows them.
@@ -27,11 +28,13 @@ Call ${T.reportFinding} once per outdated statement with:
27
28
  - file: the path of a file in <ocra_review_files>.
28
29
  - existingCode: one to five lines copied verbatim from the new version of that file, at the change that makes the guidelines wrong. Never invent or paraphrase code, never include diff markers, never give line numbers.
29
30
  - severity: "warning" when an agent following the guidelines would now fail (a command or path that no longer exists); otherwise "suggestion". Never "critical".
30
- - title: one sentence naming what the guidelines now get wrong.
31
+ - title: what the guidelines now get wrong.
31
32
  - body: the statement in the guidelines, and what is true after this change.
32
33
  - suggestion: an optional minimal update of the guidelines.
33
34
  - evidence: the facts you verified with tools, such as "package.json renames the test script to test:unit; AGENTS.md still says npm test".
34
35
 
36
+ ${FINDING_WRITING}
37
+
35
38
  If a finding would not survive a skeptical senior engineer, do not report it. Reporting nothing is a valid outcome.
36
39
 
37
40
  When every file has been reviewed, call ${T.taskDone}.`;