@open-cr-agent/core 0.21.0 → 0.22.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,41 @@
1
+ import type { OneShot } from "../agent/model-call.js";
2
+ import type { AgentCallSettings } from "../agent/settings.js";
3
+ import type { SpendLimit } from "../agent/spend-limit.js";
4
+ import type { ReviewContext, SyntaxChecker } from "../contracts.js";
5
+ import { type CallFailure } from "../errors.js";
6
+ import type { MendScope } from "../mend/gate.js";
7
+ import type { ItemOutcome, ItemReason } from "../mend/outcomes.js";
8
+ import { type MendState } from "../mend/state.js";
9
+ import type { ChangeConflicts } from "../vcs.js";
10
+ interface ConflictResult {
11
+ id: string;
12
+ conflict: string;
13
+ outcome: ItemOutcome;
14
+ reason?: ItemReason;
15
+ cause?: CallFailure;
16
+ }
17
+ export interface ConflictRound {
18
+ items: ConflictResult[];
19
+ resolved?: {
20
+ path: string;
21
+ content: string;
22
+ executable: boolean;
23
+ }[];
24
+ }
25
+ interface ConflictDeps {
26
+ ask: OneShot;
27
+ context: ReviewContext;
28
+ scope: MendScope;
29
+ syntax: SyntaxChecker;
30
+ spendLimit: Pick<SpendLimit, "mayCall">;
31
+ fixer: AgentCallSettings | undefined;
32
+ verifier: AgentCallSettings | undefined;
33
+ signal: AbortSignal;
34
+ onWarning: (warning: string) => void;
35
+ }
36
+ export declare function conflictItemId(file: {
37
+ path: string;
38
+ merged?: string;
39
+ }): string;
40
+ export declare function conflictRound(conflicts: ChangeConflicts, before: MendState, deps: ConflictDeps): Promise<ConflictRound>;
41
+ export {};
@@ -0,0 +1,118 @@
1
+ import { mapWithConcurrency } from "../agent/pool.js";
2
+ import { callFailure, errorMessage } from "../errors.js";
3
+ import { shortHash } from "../hash.js";
4
+ import { buildConflictCheckPrompt, buildConflictPrompt, CONFLICT_LIMITS, conflictVerdict, parseConflicts, resolveConflicts, tooLargeToResolve, } from "../mend/conflict.js";
5
+ import { closedAs } from "../mend/state.js";
6
+ import { isUnsafeCodePoint } from "../unsafe-text.js";
7
+ const CONCURRENCY = 3;
8
+ const CALL_TIMEOUT_MS = 180_000;
9
+ // A conflicted file as the loop's work item: the same item, with the same
10
+ // attempts, while git merges it to the same text (ADR-0078 point 8).
11
+ export function conflictItemId(file) {
12
+ return shortHash(`conflict\0${file.path}\0${shortHash(file.merged ?? "")}`);
13
+ }
14
+ // A round over the conflicts of merging the base branch into the head: one
15
+ // call on the fixer role per conflicted file answers its regions, code puts
16
+ // the file together, and one call on the verifier role checks it. Files the
17
+ // lane cannot take stop the round before any call.
18
+ export async function conflictRound(conflicts, before, deps) {
19
+ const person = (reason) => ({ outcome: "needs_human", reason });
20
+ const items = conflicts.other.map((path) => ({
21
+ id: conflictItemId({ path }),
22
+ conflict: path,
23
+ ...person("not_candidate"),
24
+ }));
25
+ const open = [];
26
+ for (const [index, file] of conflicts.files.entries()) {
27
+ const id = conflictItemId(file);
28
+ const segments = parseConflicts(file.merged, file.markerSize);
29
+ const closed = closedAs(before.items[id]);
30
+ const scoped = deps.scope.refusal(file.path);
31
+ const refused = closed
32
+ ? { outcome: closed, reason: "attempts" }
33
+ : scoped
34
+ ? person(scoped)
35
+ : !segments
36
+ ? person("not_candidate")
37
+ : index >= CONFLICT_LIMITS.files || tooLargeToResolve(segments)
38
+ ? person("too_large")
39
+ : undefined;
40
+ if (refused)
41
+ items.push({ id, conflict: file.path, ...refused });
42
+ else if (segments)
43
+ open.push({ id, file, segments });
44
+ }
45
+ const waiting = () => open.map(({ id, file }) => ({
46
+ id,
47
+ conflict: file.path,
48
+ outcome: "deferred",
49
+ reason: "conflicts",
50
+ }));
51
+ if (items.length > 0 || open.length === 0)
52
+ return { items: [...items, ...waiting()] };
53
+ const answers = await mapWithConcurrency(open, CONCURRENCY, async ({ file, segments }) => deps.spendLimit.mayCall()
54
+ ? resolveFile(file, segments, deps)
55
+ : { outcome: "deferred", reason: "no_room" });
56
+ const results = open.map(({ id, file }, i) => {
57
+ const answer = answers[i];
58
+ return "content" in answer
59
+ ? { id, conflict: file.path, outcome: "deferred", reason: "conflicts" }
60
+ : { id, conflict: file.path, ...answer };
61
+ });
62
+ if (answers.some((answer) => !("content" in answer)))
63
+ return { items: results };
64
+ return {
65
+ items: open.map(({ id, file }) => ({ id, conflict: file.path, outcome: "fixed" })),
66
+ resolved: open.map(({ file }, i) => ({
67
+ path: file.path,
68
+ content: answers[i].content,
69
+ executable: file.executable,
70
+ })),
71
+ };
72
+ }
73
+ async function resolveFile(file, segments, deps) {
74
+ const rejected = (reason, cause) => ({
75
+ outcome: "rejected",
76
+ reason,
77
+ ...(cause ? { cause } : {}),
78
+ });
79
+ const call = async (agent, prompt) => deps.ask({
80
+ tier: "standard",
81
+ agent,
82
+ call: agent === "fixer" ? deps.fixer : deps.verifier,
83
+ ...prompt,
84
+ timeoutMs: CALL_TIMEOUT_MS,
85
+ }, deps.signal);
86
+ try {
87
+ const answer = resolveConflicts(segments, await call("fixer", buildConflictPrompt(file.path, segments)));
88
+ if ("refused" in answer) {
89
+ return answer.refused === "declined"
90
+ ? rejected("declined")
91
+ : rejected("failed", "invalid_output");
92
+ }
93
+ for (const char of answer.file) {
94
+ if (isUnsafeCodePoint(char.codePointAt(0)))
95
+ return rejected("unsafe");
96
+ }
97
+ // The file parsed on the change request's side: the merge may not break it.
98
+ const ours = await deps.context.readFile(file.path);
99
+ const [was, now] = await Promise.all([
100
+ ours === undefined ? undefined : deps.syntax.errors(file.path, ours),
101
+ deps.syntax.errors(file.path, answer.file),
102
+ ]);
103
+ if (was !== undefined && now !== undefined && now > was)
104
+ return rejected("syntax");
105
+ if (!deps.spendLimit.mayCall())
106
+ return { outcome: "deferred", reason: "no_room" };
107
+ const verdict = conflictVerdict(await call("verifier", buildConflictCheckPrompt(file.path, segments, answer.resolutions)));
108
+ if (verdict === "resolves")
109
+ return { content: answer.file };
110
+ return rejected(verdict === "does_not_resolve" ? "unresolved" : verdict === "unsure" ? "unsure" : "unchecked");
111
+ }
112
+ catch (error) {
113
+ if (deps.signal.aborted)
114
+ throw error;
115
+ deps.onWarning(`resolving the conflicts of ${file.path} failed: ${errorMessage(error)}`);
116
+ return rejected("failed", callFailure(error));
117
+ }
118
+ }
@@ -0,0 +1,24 @@
1
+ import type { AgentRuntime, SyntaxChecker, Usage } from "../contracts.js";
2
+ import type { MendLevel } from "../mend/outcomes.js";
3
+ import { type MendItemResult, type MendRound } from "../mend/round.js";
4
+ import type { MendState } from "../mend/state.js";
5
+ import type { ChangeConflicts, VcsAdapter } from "../vcs.js";
6
+ import type { ReviewOptions } from "./options.js";
7
+ interface MergeOptions extends Pick<ReviewOptions, "effort" | "roles"> {
8
+ vcs: VcsAdapter;
9
+ runtime: AgentRuntime;
10
+ syntax: SyntaxChecker;
11
+ level: MendLevel;
12
+ maxCostUsd?: number;
13
+ protectedPaths?: readonly string[];
14
+ signal: AbortSignal;
15
+ onUsage: (usage: Usage) => void;
16
+ }
17
+ export declare function changeConflicts(vcs: VcsAdapter, headSha: string, warnings: string[]): Promise<ChangeConflicts | undefined>;
18
+ export declare function mergeRound(options: MergeOptions, conflicts: ChangeConflicts, round: {
19
+ headSha: string;
20
+ before: MendState;
21
+ warnings: string[];
22
+ waiting: MendItemResult[];
23
+ }): Promise<MendRound>;
24
+ export {};
@@ -0,0 +1,110 @@
1
+ import { oneShot } from "../agent/model-call.js";
2
+ import { roleCall } from "../agent/settings.js";
3
+ import { spendLimit } from "../agent/spend-limit.js";
4
+ import { errorMessage } from "../errors.js";
5
+ import { mendScope } from "../mend/gate.js";
6
+ import { nextState } from "../mend/round.js";
7
+ import { reviewContext } from "./context.js";
8
+ import { conflictRound } from "./mend-conflicts.js";
9
+ // What stands between the head and a merge of its base branch. An adapter
10
+ // that cannot tell, or a merge that cannot be read (a shallow clone, an old
11
+ // git), leaves the round to its other items, with a warning.
12
+ export async function changeConflicts(vcs, headSha, warnings) {
13
+ if (!vcs.conflicts) {
14
+ warnings.push(`the ${vcs.name} adapter reads no merge conflicts: none was worked on`);
15
+ return undefined;
16
+ }
17
+ try {
18
+ return await vcs.conflicts(headSha);
19
+ }
20
+ catch (error) {
21
+ warnings.push(`reading the change's merge conflicts failed: ${errorMessage(error)}`);
22
+ return undefined;
23
+ }
24
+ }
25
+ // A round over the change's merge conflicts, and over nothing else: its
26
+ // commit is a merge of the base branch, so the round's other items wait for
27
+ // the next one (`waiting`, deferred). The merge is written only when every
28
+ // conflicted file is resolved and checked.
29
+ export async function mergeRound(options, conflicts, round) {
30
+ const { vcs } = options;
31
+ const { headSha, before, warnings } = round;
32
+ const diffs = await vcs.getDiff();
33
+ const remaining = options.maxCostUsd === undefined ? undefined : options.maxCostUsd - before.costUsd;
34
+ const limit = spendLimit(remaining);
35
+ let spent = 0;
36
+ const ask = oneShot(options.runtime, (usage) => {
37
+ limit.charge(usage);
38
+ spent += usage.costUsd;
39
+ options.onUsage(usage);
40
+ });
41
+ const answered = await conflictRound(conflicts, before, {
42
+ ask,
43
+ context: reviewContext(vcs, diffs),
44
+ scope: mendScope(diffs, options.protectedPaths),
45
+ syntax: options.syntax,
46
+ spendLimit: limit,
47
+ fixer: roleCall("fixer", options),
48
+ verifier: roleCall("verifier", options),
49
+ signal: options.signal,
50
+ onWarning: (w) => warnings.push(w),
51
+ });
52
+ const ended = (outcome, items, more = {}) => ({
53
+ headSha,
54
+ outcome,
55
+ mergeParent: conflicts.mergeParent,
56
+ items: [...items, ...round.waiting],
57
+ state: nextState(before, items, spent),
58
+ warnings,
59
+ ...more,
60
+ });
61
+ const { resolved } = answered;
62
+ if (!resolved)
63
+ return ended("nothing", answered.items);
64
+ if (options.level === "propose") {
65
+ const content = new Map(resolved.map((file) => [file.path, file.content]));
66
+ return ended("proposed", answered.items.map((item) => ({
67
+ ...item,
68
+ outcome: "proposed",
69
+ resolved: content.get(item.conflict),
70
+ })));
71
+ }
72
+ if (!vcs.commit)
73
+ return ended("not_writable", deferred(answered.items, "not_writable"));
74
+ const result = await vcs.commit({
75
+ parent: headSha,
76
+ mergeParent: conflicts.mergeParent,
77
+ message: mergeMessage(conflicts.mergeParent, resolved),
78
+ files: resolved.map((file) => ({ ...file, created: false })),
79
+ });
80
+ if (!result.committed)
81
+ return ended(result.outcome, deferred(answered.items, result.outcome));
82
+ await vcs
83
+ .note?.({
84
+ commitSha: result.sha,
85
+ fixed: answered.items.map((item) => ({ title: "merge conflict", file: item.conflict })),
86
+ left: [],
87
+ })
88
+ .catch((error) => warnings.push(`the round's note was not posted: ${errorMessage(error)}`));
89
+ return ended("committed", answered.items, { sha: result.sha });
90
+ }
91
+ function deferred(items, reason) {
92
+ return items.map(({ id, conflict }) => ({
93
+ id,
94
+ ...(conflict ? { conflict } : {}),
95
+ outcome: "deferred",
96
+ reason,
97
+ }));
98
+ }
99
+ // Paths come from the change: one line each, behind a list marker, so none
100
+ // can add a trailer or a line of its own.
101
+ function mergeMessage(mergeParent, files) {
102
+ const clean = (text) => text.replace(/[\p{Cc}\p{Cf}\u2028\u2029\s]+/gu, " ").trim();
103
+ return [
104
+ `Merge ${mergeParent.slice(0, 12)} of the base branch, conflicts resolved by ocra`,
105
+ "",
106
+ ...files.map((file) => `- ${clean(file.path)}`),
107
+ "",
108
+ "ocra ran nothing from the repository to check this merge: the change request's own checks do.",
109
+ ].join("\n");
110
+ }
@@ -1,35 +1,16 @@
1
1
  import type { AgentRuntime, SyntaxChecker, Usage } from "../contracts.js";
2
- import { type CallFailure } from "../errors.js";
3
- import { type Hunk } from "../mend/patch.js";
4
- import { type MendState, type RoundStop } from "../mend/state.js";
2
+ import type { MendLevel } from "../mend/outcomes.js";
3
+ import { type MendRound } from "../mend/round.js";
4
+ import { type MendState } from "../mend/state.js";
5
5
  import type { VcsAdapter } from "../vcs.js";
6
- import { type StoredFinding } from "./fix-finding.js";
6
+ import type { StoredFinding } from "./fix-finding.js";
7
7
  import type { ReviewOptions } from "./options.js";
8
- export declare const MEND_LEVELS: readonly ["propose", "commit"];
9
- export type MendLevel = (typeof MEND_LEVELS)[number];
10
- export declare const MEND_ITEM_OUTCOMES: readonly ["fixed", "proposed", "rejected", "deferred", "needs_human", "gone"];
11
- type ItemOutcome = (typeof MEND_ITEM_OUTCOMES)[number];
12
- export declare const MEND_ITEM_REASONS: ("attempts" | "declined" | "failed" | "head_moved" | "no_parser" | "no_room" | "not_candidate" | "not_writable" | "out_of_scope" | "overlap" | "protected" | "stale" | "syntax" | "tamper" | "too_large" | "unchanged" | "unchecked" | "unresolved" | "unsafe" | "unsure")[];
13
- type ItemReason = (typeof MEND_ITEM_REASONS)[number];
14
- export declare const MEND_OUTCOMES: readonly ["committed", "proposed", "nothing", "stopped", "head_moved", "not_writable"];
15
- interface MendItemResult {
16
- id: string;
17
- outcome: ItemOutcome;
18
- reason?: ItemReason;
19
- cause?: CallFailure;
20
- edits?: readonly Hunk[];
21
- }
22
- export interface MendRound {
23
- headSha: string;
24
- outcome: (typeof MEND_OUTCOMES)[number];
25
- stopped?: RoundStop;
26
- sha?: string;
27
- items: MendItemResult[];
28
- state: MendState;
29
- warnings: string[];
30
- }
8
+ export { MEND_ITEM_OUTCOMES, MEND_ITEM_REASONS, MEND_LEVELS, MEND_OUTCOMES, type MendLevel, } from "../mend/outcomes.js";
9
+ export type { MendRound } from "../mend/round.js";
31
10
  interface MendOptions extends Pick<ReviewOptions, "effort" | "roles"> {
32
11
  findings: readonly StoredFinding[];
12
+ checks?: boolean;
13
+ conflicts?: boolean;
33
14
  vcs: VcsAdapter;
34
15
  runtime: AgentRuntime;
35
16
  syntax: SyntaxChecker;
@@ -42,4 +23,3 @@ interface MendOptions extends Pick<ReviewOptions, "effort" | "roles"> {
42
23
  onUsage: (usage: Usage) => void;
43
24
  }
44
25
  export declare function mendRound(options: MendOptions): Promise<MendRound>;
45
- export {};