@open-cr-agent/core 0.20.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.
Files changed (44) hide show
  1. package/dist/agent/model-call.js +5 -2
  2. package/dist/contracts.d.ts +17 -0
  3. package/dist/errors.d.ts +10 -0
  4. package/dist/errors.js +31 -0
  5. package/dist/fix/propose.d.ts +2 -0
  6. package/dist/fix/propose.js +6 -5
  7. package/dist/index.d.ts +5 -5
  8. package/dist/index.js +2 -2
  9. package/dist/internal.d.ts +1 -0
  10. package/dist/internal.js +1 -0
  11. package/dist/mend/agent-lane.d.ts +26 -0
  12. package/dist/mend/agent-lane.js +138 -0
  13. package/dist/mend/checks.d.ts +11 -0
  14. package/dist/mend/checks.js +48 -0
  15. package/dist/mend/conflict.d.ts +36 -0
  16. package/dist/mend/conflict.js +204 -0
  17. package/dist/mend/outcomes.d.ts +7 -0
  18. package/dist/mend/outcomes.js +43 -0
  19. package/dist/mend/round.d.ts +25 -0
  20. package/dist/mend/round.js +20 -0
  21. package/dist/mend/workspace.d.ts +18 -0
  22. package/dist/mend/workspace.js +175 -0
  23. package/dist/pipeline/fix-finding.d.ts +3 -0
  24. package/dist/pipeline/fix-finding.js +6 -1
  25. package/dist/pipeline/mend-agent.d.ts +22 -0
  26. package/dist/pipeline/mend-agent.js +35 -0
  27. package/dist/pipeline/mend-attempt.d.ts +33 -0
  28. package/dist/pipeline/mend-attempt.js +103 -0
  29. package/dist/pipeline/mend-conflicts.d.ts +41 -0
  30. package/dist/pipeline/mend-conflicts.js +118 -0
  31. package/dist/pipeline/mend-merge.d.ts +24 -0
  32. package/dist/pipeline/mend-merge.js +110 -0
  33. package/dist/pipeline/mend.d.ts +8 -26
  34. package/dist/pipeline/mend.js +92 -125
  35. package/dist/plugin/registry.d.ts +2 -2
  36. package/dist/plugin/types.d.ts +1 -7
  37. package/dist/review/prompt-text.d.ts +1 -1
  38. package/dist/review/prompt-text.js +7 -0
  39. package/dist/runtime/failback.js +11 -3
  40. package/dist/runtime/text-tools.d.ts +1 -1
  41. package/dist/runtime/tools.d.ts +2 -1
  42. package/dist/runtime/tools.js +2 -0
  43. package/dist/vcs.d.ts +36 -0
  44. package/package.json +1 -1
@@ -0,0 +1,103 @@
1
+ import { gate } from "../mend/gate.js";
2
+ import { MEND_LIMITS } from "../mend/state.js";
3
+ import { fixAtHead } from "./fix-finding.js";
4
+ import { agentPatch } from "./mend-agent.js";
5
+ // A person decides these: no later round at this head answers differently.
6
+ const FOR_A_PERSON = new Set([
7
+ "not_candidate",
8
+ "no_parser",
9
+ "out_of_scope",
10
+ "protected",
11
+ "too_large",
12
+ "tamper",
13
+ ]);
14
+ // Why the local lane wrote nothing for a finding an edit may still fix: it
15
+ // spans more than the lane takes, or needs lines elsewhere.
16
+ const NOT_LOCAL = new Set([
17
+ "not_candidate",
18
+ "declined",
19
+ "too_large",
20
+ ]);
21
+ // One item through its lane, the gate and the verification steps.
22
+ export async function attempt(item, head, steps, deps) {
23
+ const refuse = (reason, cause) => ({
24
+ outcome: reason === "stale" ? "gone" : FOR_A_PERSON.has(reason) ? "needs_human" : "rejected",
25
+ reason,
26
+ ...(cause ? { cause } : {}),
27
+ });
28
+ if ("finding" in item) {
29
+ const outside = head.scope.refusal(item.finding.file);
30
+ if (outside)
31
+ return refuse(outside);
32
+ }
33
+ const written = "finding" in item
34
+ ? await write(item.finding, head, deps)
35
+ : await writeForCheck(item.id, item.check, head, deps);
36
+ if (!("patch" in written)) {
37
+ return written.reason === "no_room"
38
+ ? { outcome: "deferred", reason: "no_room" }
39
+ : refuse(written.reason, written.cause);
40
+ }
41
+ const { patch } = written;
42
+ const gated = await gate(patch, head.contents, head.scope, deps.syntax, MEND_LIMITS);
43
+ if (gated)
44
+ return refuse(gated);
45
+ const subject = "finding" in item
46
+ ? { title: item.finding.title, body: item.finding.body }
47
+ : { title: `The check "${item.check.name}" fails on this change`, body: item.check.log };
48
+ for (const step of steps) {
49
+ if (!deps.spendLimit.mayCall())
50
+ return { outcome: "deferred", reason: "no_room" };
51
+ const refused = await step({ ...subject, patch, heads: head.contents }, deps.signal);
52
+ if (refused)
53
+ return refuse(refused);
54
+ }
55
+ return { patch };
56
+ }
57
+ // The patch for a failed check: only a task that can read the code the log
58
+ // names writes one, so a runtime without tasks' own tools, or a check that
59
+ // gave no log, leaves it to a person.
60
+ async function writeForCheck(id, check, head, deps) {
61
+ if (!deps.runtime.toolsets || check.log === "")
62
+ return { reason: "not_candidate" };
63
+ const changed = head.diffs.flatMap((d) => (d.newPath ? [d.newPath] : []));
64
+ return fromAgent({ id, title: check.name, body: "", check: { log: check.log, changed } }, head, deps);
65
+ }
66
+ async function fromAgent(item, head, deps) {
67
+ const edited = await agentPatch(item, { ...deps, context: head.context, scope: head.scope });
68
+ if (!("patch" in edited)) {
69
+ if (edited.warning)
70
+ deps.onWarning(edited.warning);
71
+ return edited;
72
+ }
73
+ for (const [path, content] of edited.heads)
74
+ head.contents.set(path, content);
75
+ return edited;
76
+ }
77
+ // The patch for one finding, by the smallest lane that can write it: the fix
78
+ // stage's completion for a local edit, else a task with the edit tool, where
79
+ // the runtime runs one.
80
+ async function write(finding, head, deps) {
81
+ const fixed = await fixAtHead(finding, { ...deps, diffs: head.diffs, context: head.context });
82
+ for (const warning of fixed.warnings)
83
+ deps.onWarning(warning);
84
+ if ("fix" in fixed) {
85
+ const content = await head.context.readFile(finding.file);
86
+ if (content === undefined)
87
+ return { reason: "stale" };
88
+ head.contents.set(finding.file, content);
89
+ return {
90
+ patch: { item: finding.fingerprint, hunks: [{ path: finding.file, ...fixed.fix }] },
91
+ };
92
+ }
93
+ if (!deps.runtime.toolsets || !NOT_LOCAL.has(fixed.reason))
94
+ return fixed;
95
+ return fromAgent({
96
+ id: finding.fingerprint,
97
+ file: finding.file,
98
+ title: finding.title,
99
+ body: finding.body,
100
+ code: finding.existingCode,
101
+ suggestion: finding.suggestion,
102
+ }, head, deps);
103
+ }
@@ -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,33 +1,16 @@
1
1
  import type { AgentRuntime, SyntaxChecker, Usage } from "../contracts.js";
2
- import { type Hunk } from "../mend/patch.js";
3
- 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";
4
5
  import type { VcsAdapter } from "../vcs.js";
5
- import { type StoredFinding } from "./fix-finding.js";
6
+ import type { StoredFinding } from "./fix-finding.js";
6
7
  import type { ReviewOptions } from "./options.js";
7
- export declare const MEND_LEVELS: readonly ["propose", "commit"];
8
- export type MendLevel = (typeof MEND_LEVELS)[number];
9
- export declare const MEND_ITEM_OUTCOMES: readonly ["fixed", "proposed", "rejected", "deferred", "needs_human", "gone"];
10
- type ItemOutcome = (typeof MEND_ITEM_OUTCOMES)[number];
11
- 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")[];
12
- type ItemReason = (typeof MEND_ITEM_REASONS)[number];
13
- export declare const MEND_OUTCOMES: readonly ["committed", "proposed", "nothing", "stopped", "head_moved", "not_writable"];
14
- interface MendItemResult {
15
- id: string;
16
- outcome: ItemOutcome;
17
- reason?: ItemReason;
18
- edits?: readonly Hunk[];
19
- }
20
- export interface MendRound {
21
- headSha: string;
22
- outcome: (typeof MEND_OUTCOMES)[number];
23
- stopped?: RoundStop;
24
- sha?: string;
25
- items: MendItemResult[];
26
- state: MendState;
27
- warnings: string[];
28
- }
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";
29
10
  interface MendOptions extends Pick<ReviewOptions, "effort" | "roles"> {
30
11
  findings: readonly StoredFinding[];
12
+ checks?: boolean;
13
+ conflicts?: boolean;
31
14
  vcs: VcsAdapter;
32
15
  runtime: AgentRuntime;
33
16
  syntax: SyntaxChecker;
@@ -40,4 +23,3 @@ interface MendOptions extends Pick<ReviewOptions, "effort" | "roles"> {
40
23
  onUsage: (usage: Usage) => void;
41
24
  }
42
25
  export declare function mendRound(options: MendOptions): Promise<MendRound>;
43
- export {};