@open-cr-agent/core 0.21.0 → 0.23.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.
@@ -2,75 +2,26 @@ import { oneShot } from "../agent/model-call.js";
2
2
  import { mapWithConcurrency } from "../agent/pool.js";
3
3
  import { roleCall } from "../agent/settings.js";
4
4
  import { spendLimit } from "../agent/spend-limit.js";
5
- import { OcraError } from "../errors.js";
6
- import { FIX_REJECTIONS } from "../fix/check.js";
5
+ import { errorMessage, OcraError } from "../errors.js";
7
6
  import { headMode } from "../generate/targets.js";
8
- import { GATE_REJECTIONS, gate, mendScope } from "../mend/gate.js";
7
+ import { CHECK_LIMITS, checkItemId } from "../mend/checks.js";
8
+ import { mendScope } from "../mend/gate.js";
9
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";
10
+ import { nextState } from "../mend/round.js";
11
+ import { closedAs, EMPTY_STATE, MEND_LIMITS, roundStop } from "../mend/state.js";
12
+ import { verifierStep } from "../mend/verify.js";
12
13
  import { oneLine } from "../review/prompt-text.js";
13
14
  import { reviewContext } from "./context.js";
14
- import { fixAtHead } from "./fix-finding.js";
15
- import { agentPatch } from "./mend-agent.js";
15
+ import { attempt } from "./mend-attempt.js";
16
+ import { changeConflicts, mergeRound } from "./mend-merge.js";
17
+ export { MEND_ITEM_OUTCOMES, MEND_ITEM_REASONS, MEND_LEVELS, MEND_OUTCOMES, } from "../mend/outcomes.js";
16
18
  const CONCURRENCY = 3;
17
19
  const SUBJECT_TITLE_CHARS = 100;
18
- // `propose` ends a round with its checked changes for a person to commit;
19
- // `commit` writes them to the change request's branch.
20
- export const MEND_LEVELS = ["propose", "commit"];
21
- // fixed, proposed: its patch is in the round's commit, or in what the round
22
- // proposes. rejected: this round wrote no patch that passed; another may.
23
- // deferred: not tried, or tried and not written; no attempt is counted.
24
- // needs_human, gone: closed, for a person or because its code is gone.
25
- export const MEND_ITEM_OUTCOMES = [
26
- "fixed",
27
- "proposed",
28
- "rejected",
29
- "deferred",
30
- "needs_human",
31
- "gone",
32
- ];
33
- export const MEND_ITEM_REASONS = [
34
- ...new Set([
35
- ...FIX_REJECTIONS,
36
- "not_candidate",
37
- ...GATE_REJECTIONS,
38
- ...VERIFICATION_REJECTIONS,
39
- "overlap",
40
- "no_room",
41
- "attempts",
42
- "head_moved",
43
- "not_writable",
44
- ]),
45
- ];
46
- export const MEND_OUTCOMES = [
47
- "committed",
48
- "proposed",
49
- "nothing",
50
- "stopped",
51
- "head_moved",
52
- "not_writable",
53
- ];
54
- // A person decides these: no later round at this head answers differently.
55
- const FOR_A_PERSON = new Set([
56
- "not_candidate",
57
- "no_parser",
58
- "out_of_scope",
59
- "protected",
60
- "too_large",
61
- "tamper",
62
- ]);
63
- // Why the local lane wrote nothing for a finding an edit may still fix: it
64
- // spans more than the lane takes, or needs lines elsewhere.
65
- const NOT_LOCAL = new Set([
66
- "not_candidate",
67
- "declined",
68
- "too_large",
69
- ]);
70
- // One round of the fix loop (ADR-0078) over accepted findings: each open
71
- // finding gets a patch from its lane, the gate and the verifier decide what
72
- // is kept, and the kept patches become one commit from the head they were
73
- // made at. Nothing from the change runs.
20
+ // One round of the fix loop (ADR-0078) over accepted findings and, when
21
+ // asked, the checks that failed on the head: each open item gets a patch
22
+ // from its lane, the gate and the verifier decide what is kept, and the kept
23
+ // patches become one commit from the head they were made at. Nothing from
24
+ // the change runs.
74
25
  export async function mendRound(options) {
75
26
  const { vcs } = options;
76
27
  const before = options.state ?? EMPTY_STATE;
@@ -94,24 +45,37 @@ export async function mendRound(options) {
94
45
  const stopped = roundStop(before, options.maxCostUsd);
95
46
  if (stopped)
96
47
  return ended({ outcome: "stopped", stopped });
97
- const findings = unique(options.findings);
48
+ const conflicts = options.conflicts ? await changeConflicts(vcs, headSha, warnings) : undefined;
49
+ if (conflicts) {
50
+ const waiting = unique(options.findings)
51
+ .filter((f) => !closedAs(before.items[f.fingerprint]))
52
+ .map((f) => ({ id: f.fingerprint, outcome: "deferred", reason: "conflicts" }));
53
+ return mergeRound(options, conflicts, { headSha, before, warnings, waiting });
54
+ }
55
+ const checks = options.checks ? await failedChecks(vcs, headSha, warnings) : undefined;
56
+ const items = [
57
+ ...unique(options.findings).map((finding) => ({ id: finding.fingerprint, finding })),
58
+ ...(checks?.failed ?? []).map((check) => ({ id: checkItemId(check), check })),
59
+ ];
60
+ const named = (item) => ("check" in item ? { check: item.check.name } : {});
98
61
  const results = new Map();
99
62
  const open = [];
100
- for (const finding of findings) {
101
- const id = finding.fingerprint;
63
+ for (const item of items) {
64
+ const { id } = item;
102
65
  const closed = closedAs(before.items[id]);
103
66
  if (closed) {
104
67
  const used = before.items[id]?.closed === undefined;
105
68
  results.set(id, { id, outcome: closed, ...(used ? { reason: "attempts" } : {}) });
106
69
  }
107
70
  else if (open.length < MEND_LIMITS.itemsPerRound)
108
- open.push(finding);
71
+ open.push(item);
109
72
  else
110
73
  results.set(id, { id, outcome: "deferred", reason: "no_room" });
111
74
  }
112
- const listed = () => findings.map((f) => results.get(f.fingerprint));
113
- if (open.length === 0)
114
- return ended({ outcome: "nothing", items: listed() });
75
+ const listed = () => items.map((item) => ({ ...results.get(item.id), ...named(item) }));
76
+ if (open.length === 0) {
77
+ return ended({ outcome: checks?.pending ? "waiting" : "nothing", items: listed() });
78
+ }
115
79
  const diffs = await vcs.getDiff();
116
80
  const head = {
117
81
  diffs,
@@ -134,10 +98,10 @@ export async function mendRound(options) {
134
98
  const steps = [
135
99
  verifierStep(ask, roleCall("verifier", options), (w) => warnings.push(w)),
136
100
  ];
137
- const attempts = await mapWithConcurrency(open, CONCURRENCY, async (finding) => {
101
+ const attempts = await mapWithConcurrency(open, CONCURRENCY, async (item) => {
138
102
  if (!limit.mayCall())
139
103
  return { outcome: "deferred", reason: "no_room" };
140
- return attempt(finding, head, steps, {
104
+ return attempt(item, head, steps, {
141
105
  runtime: options.runtime,
142
106
  syntax: options.syntax,
143
107
  spendLimit: limit,
@@ -148,12 +112,12 @@ export async function mendRound(options) {
148
112
  });
149
113
  });
150
114
  const patches = [];
151
- open.forEach((finding, i) => {
115
+ open.forEach(({ id }, i) => {
152
116
  const tried = attempts[i];
153
117
  if ("patch" in tried)
154
118
  patches.push(tried.patch);
155
119
  else
156
- results.set(finding.fingerprint, { id: finding.fingerprint, ...tried });
120
+ results.set(id, { id, ...tried });
157
121
  });
158
122
  const composed = composePatches(patches, head.contents, MEND_LIMITS);
159
123
  for (const { item, reason } of composed.left) {
@@ -164,7 +128,7 @@ export async function mendRound(options) {
164
128
  round =
165
129
  options.level === "propose"
166
130
  ? { outcome: "proposed" }
167
- : await commit(vcs, headSha, composed.changes, kept(findings, composed.kept), diffs);
131
+ : await commit(vcs, headSha, composed.changes, items.filter((item) => composed.kept.includes(item.id)), diffs);
168
132
  }
169
133
  for (const patch of patches.filter((p) => composed.kept.includes(p.item))) {
170
134
  const id = patch.item;
@@ -174,71 +138,31 @@ export async function mendRound(options) {
174
138
  ? { id, outcome: "proposed", edits: patch.hunks }
175
139
  : { id, outcome: "deferred", reason: round.outcome });
176
140
  }
177
- return ended({ ...round, items: listed(), state: nextState(before, results, spent) });
178
- }
179
- // One finding through its lane, the gate and the verification steps.
180
- async function attempt(finding, head, steps, deps) {
181
- const refuse = (reason, cause) => ({
182
- outcome: reason === "stale" ? "gone" : FOR_A_PERSON.has(reason) ? "needs_human" : "rejected",
183
- reason,
184
- ...(cause ? { cause } : {}),
185
- });
186
- const outside = head.scope.refusal(finding.file);
187
- if (outside)
188
- return refuse(outside);
189
- const written = await write(finding, head, deps);
190
- if (!("patch" in written)) {
191
- return written.reason === "no_room"
192
- ? { outcome: "deferred", reason: "no_room" }
193
- : refuse(written.reason, written.cause);
194
- }
195
- const { patch } = written;
196
- const gated = await gate(patch, head.contents, head.scope, deps.syntax, MEND_LIMITS);
197
- if (gated)
198
- return refuse(gated);
199
- for (const step of steps) {
200
- if (!deps.spendLimit.mayCall())
201
- return { outcome: "deferred", reason: "no_room" };
202
- const refused = await step({ title: finding.title, body: finding.body, patch, heads: head.contents }, deps.signal);
203
- if (refused)
204
- return refuse(refused);
141
+ if (round.outcome === "committed" && round.sha) {
142
+ await vcs
143
+ .note?.(roundNote(round.sha, items, results))
144
+ .catch((error) => warnings.push(`the round's note was not posted: ${errorMessage(error)}`));
205
145
  }
206
- return { patch };
146
+ return ended({ ...round, items: listed(), state: nextState(before, results.values(), spent) });
207
147
  }
208
- // The patch for one finding, by the smallest lane that can write it: the fix
209
- // stage's completion for a local edit, else a task with the edit tool, where
210
- // the runtime runs one.
211
- async function write(finding, head, deps) {
212
- const fixed = await fixAtHead(finding, { ...deps, diffs: head.diffs, context: head.context });
213
- for (const warning of fixed.warnings)
214
- deps.onWarning(warning);
215
- if ("fix" in fixed) {
216
- const content = await head.context.readFile(finding.file);
217
- if (content === undefined)
218
- return { reason: "stale" };
219
- head.contents.set(finding.file, content);
220
- return {
221
- patch: { item: finding.fingerprint, hunks: [{ path: finding.file, ...fixed.fix }] },
222
- };
223
- }
224
- if (!deps.runtime.toolsets || !NOT_LOCAL.has(fixed.reason))
225
- return fixed;
226
- const edited = await agentPatch({
227
- id: finding.fingerprint,
228
- file: finding.file,
229
- title: finding.title,
230
- body: finding.body,
231
- code: finding.existingCode,
232
- suggestion: finding.suggestion,
233
- }, { ...deps, context: head.context, scope: head.scope });
234
- if (!("patch" in edited)) {
235
- if (edited.warning)
236
- deps.onWarning(edited.warning);
237
- return edited;
148
+ function roundNote(commitSha, items, results) {
149
+ const note = { commitSha, fixed: [], left: [] };
150
+ for (const item of items) {
151
+ const named = "check" in item
152
+ ? { title: item.check.name, check: true }
153
+ : { title: item.finding.title, file: item.finding.file };
154
+ const result = results.get(item.id);
155
+ if (result?.outcome === "fixed")
156
+ note.fixed.push(named);
157
+ else if (result) {
158
+ note.left.push({
159
+ ...named,
160
+ outcome: result.outcome,
161
+ ...(result.reason ? { reason: result.reason } : {}),
162
+ });
163
+ }
238
164
  }
239
- for (const [path, content] of edited.heads)
240
- head.contents.set(path, content);
241
- return edited;
165
+ return note;
242
166
  }
243
167
  async function commit(vcs, parent, changes, fixed, diffs) {
244
168
  if (!vcs.commit)
@@ -260,41 +184,46 @@ function executable(path, diffs) {
260
184
  const diff = diffs.find((d) => d.newPath === path);
261
185
  return diff !== undefined && headMode(diff) === "100755";
262
186
  }
263
- // Titles and paths come from a review of the change: one line each, cut, and
264
- // behind a list marker, so none can add a trailer or a line of its own.
187
+ // Titles, paths and check names come from the change and its platform: one
188
+ // line each, cut, and behind a list marker, so none can add a trailer or a
189
+ // line of its own.
265
190
  function commitMessage(fixed) {
266
191
  const clean = (text) => oneLine(text).replace(/[\p{Cc}\p{Cf}\u2028\u2029]+/gu, " ");
192
+ const title = (text) => clean(text).slice(0, SUBJECT_TITLE_CHARS);
193
+ const count = (n, noun) => `${n} ${noun}${n === 1 ? "" : "s"}`;
194
+ const checks = fixed.filter((item) => "check" in item).length;
195
+ const findings = fixed.length - checks;
196
+ const what = [
197
+ ...(findings > 0 ? [count(findings, "finding")] : []),
198
+ ...(checks > 0 ? [count(checks, "failed check")] : []),
199
+ ].join(" and ");
267
200
  return [
268
- `fix: apply ocra's fixes for ${fixed.length} finding${fixed.length === 1 ? "" : "s"}`,
201
+ `fix: apply ocra's fixes for ${what}`,
269
202
  "",
270
- ...fixed.map((f) => `- ${clean(f.file)}: ${clean(f.title).slice(0, SUBJECT_TITLE_CHARS)}`),
203
+ ...fixed.map((item) => "check" in item
204
+ ? `- check: ${title(item.check.name)}`
205
+ : `- ${clean(item.finding.file)}: ${title(item.finding.title)}`),
271
206
  "",
272
207
  "ocra ran nothing from the repository to check these edits: the change request's own checks do.",
273
208
  ].join("\n");
274
209
  }
275
- function kept(findings, ids) {
276
- return findings.filter((f) => ids.includes(f.fingerprint));
210
+ // What failed on the head, at most the checks a round reads. A platform that
211
+ // cannot be asked leaves the round to its findings, with a warning.
212
+ async function failedChecks(vcs, headSha, warnings) {
213
+ if (!vcs.checks) {
214
+ warnings.push(`the ${vcs.name} adapter reads no checks: none was worked on`);
215
+ return undefined;
216
+ }
217
+ try {
218
+ const checks = await vcs.checks(headSha);
219
+ return { ...checks, failed: checks.failed.slice(0, CHECK_LIMITS.checks) };
220
+ }
221
+ catch (error) {
222
+ warnings.push(`reading the change's checks failed: ${errorMessage(error)}`);
223
+ return undefined;
224
+ }
277
225
  }
278
226
  function unique(findings) {
279
227
  const seen = new Set();
280
228
  return findings.filter((f) => !seen.has(f.fingerprint) && seen.add(f.fingerprint));
281
229
  }
282
- // A deferred item was not tried, or its patch was not written: its attempt
283
- // is not counted, so a person's push or a full round costs it nothing.
284
- function nextState(before, results, spent) {
285
- const items = { ...before.items };
286
- for (const { id, outcome } of results.values()) {
287
- const was = items[id] ?? { attempts: 0 };
288
- if (outcome === "deferred" || was.closed)
289
- continue;
290
- const used = closedAs(was);
291
- if (used)
292
- items[id] = { ...was, closed: used };
293
- else if (outcome === "needs_human" || outcome === "gone") {
294
- items[id] = { attempts: was.attempts + 1, closed: outcome };
295
- }
296
- else
297
- items[id] = { attempts: was.attempts + 1 };
298
- }
299
- return { rounds: before.rounds + 1, costUsd: before.costUsd + spent, items };
300
- }
@@ -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", "replacement", "edit", "diff", "file_excerpt", "related_code", "callers", "analyzer_results", "review_plan", "reply", "thread", "question", "merge_checks", "check", "tool_result"];
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", "check_log", "conflict", "lines_before", "lines_after", "ancestor", "pull_request", "target", "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;
@@ -50,6 +50,13 @@ const SECTIONS = [
50
50
  "question",
51
51
  "merge_checks",
52
52
  "check",
53
+ "check_log",
54
+ "conflict",
55
+ "lines_before",
56
+ "lines_after",
57
+ "ancestor",
58
+ "pull_request",
59
+ "target",
53
60
  "tool_result",
54
61
  ];
55
62
  // Characters a tokenizer may drop or a model may read past: whitespace,
package/dist/vcs.d.ts CHANGED
@@ -25,6 +25,7 @@ export type Mention = {
25
25
  };
26
26
  export interface ChangeCommit {
27
27
  parent: string;
28
+ mergeParent?: string;
28
29
  message: string;
29
30
  files: readonly {
30
31
  path: string;
@@ -41,6 +42,38 @@ export type CommitResult = {
41
42
  outcome: "head_moved" | "not_writable";
42
43
  reason: string;
43
44
  };
45
+ export interface FailedCheck {
46
+ name: string;
47
+ log: string;
48
+ }
49
+ export interface ChangeChecks {
50
+ pending: boolean;
51
+ failed: FailedCheck[];
52
+ }
53
+ export interface ConflictedFile {
54
+ path: string;
55
+ merged: string;
56
+ markerSize: number;
57
+ executable: boolean;
58
+ }
59
+ export interface ChangeConflicts {
60
+ mergeParent: string;
61
+ files: ConflictedFile[];
62
+ other: string[];
63
+ }
64
+ export interface RoundNoteItem {
65
+ title: string;
66
+ file?: string;
67
+ check?: boolean;
68
+ }
69
+ export interface RoundNote {
70
+ commitSha: string;
71
+ fixed: RoundNoteItem[];
72
+ left: (RoundNoteItem & {
73
+ outcome: string;
74
+ reason?: string;
75
+ })[];
76
+ }
44
77
  export interface VcsAdapter {
45
78
  readonly name: string;
46
79
  getChangeRequest(): Promise<ChangeRequest>;
@@ -54,5 +87,8 @@ export interface VcsAdapter {
54
87
  mention?(ref: MentionRef): Promise<Mention>;
55
88
  listFiles?(dir: string): Promise<string[]>;
56
89
  commit?(commit: ChangeCommit): Promise<CommitResult>;
90
+ conflicts?(headSha: string): Promise<ChangeConflicts | undefined>;
91
+ note?(round: RoundNote): Promise<void>;
92
+ checks?(headSha: string): Promise<ChangeChecks>;
57
93
  linkedTasks?(): Promise<LinkedTask[]>;
58
94
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-cr-agent/core",
3
- "version": "0.21.0",
3
+ "version": "0.23.0",
4
4
  "description": "Domain types, review pipeline stages and plugin contracts for Open-CR-Agent",
5
5
  "keywords": [
6
6
  "code-review",