@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
@@ -1,14 +1,17 @@
1
1
  import { roleCall } from "../agent/settings.js";
2
2
  import { judgeFindings } from "../judge/judge.js";
3
3
  import { stillOpen } from "../rereview/reconcile.js";
4
- import { markUnchecked, verifyFindings } from "../verify/verify.js";
4
+ import { verifyRemaining } from "../verify/early.js";
5
+ import { markUnchecked } from "../verify/verify.js";
6
+ import { verifyOptions } from "./execute-stage.js";
5
7
  // Verify fact-checks the findings, then the judge merges, filters and
6
8
  // recalibrates them and gives the verdict.
7
- export async function checkStage(filtered, context) {
9
+ export async function checkStage(filtered, early, context) {
8
10
  context.emit({ type: "stage_started", stage: "verify" });
9
- const verification = hidePreExisting(await verify(filtered, context), context.settings);
11
+ const checked = await early?.result();
12
+ const verification = hidePreExisting(await verify(filtered, checked?.verification, context), context.settings);
10
13
  context.emit({ type: "stage_started", stage: "judge" });
11
- const judged = await judge(verification, filtered, context);
14
+ const judged = await judge(verification, filtered, checked?.settled, context);
12
15
  for (const usage of judged.usage)
13
16
  context.spendLimit.charge(usage);
14
17
  return {
@@ -18,7 +21,8 @@ export async function checkStage(filtered, context) {
18
21
  warnings: [...verification.warnings, ...judged.warnings],
19
22
  };
20
23
  }
21
- async function verify({ reconciled }, { options, settings, plan, spendLimit, signal, emit }) {
24
+ async function verify({ reconciled }, early, context) {
25
+ const { settings, emit } = context;
22
26
  if (!settings.verify) {
23
27
  return {
24
28
  checked: 0,
@@ -29,15 +33,7 @@ async function verify({ reconciled }, { options, settings, plan, spendLimit, sig
29
33
  warnings: [],
30
34
  };
31
35
  }
32
- const verification = await verifyFindings(reconciled.findings, {
33
- runtime: options.runtime,
34
- diffs: plan.selected,
35
- context: plan.context,
36
- signal,
37
- concurrency: settings.concurrency,
38
- spendLimit,
39
- call: roleCall("verifier", options),
40
- });
36
+ const verification = await verifyRemaining(reconciled.findings, early, verifyOptions(context));
41
37
  if (verification.checked > 0) {
42
38
  emit({
43
39
  type: "verification_finished",
@@ -63,7 +59,7 @@ function hidePreExisting(verification, settings) {
63
59
  ],
64
60
  };
65
61
  }
66
- async function judge(verification, { reconciled, nothingReviewed }, { options, settings, plan, spendLimit, signal, emit }) {
62
+ async function judge(verification, { reconciled, nothingReviewed }, settled, { options, settings, plan, spendLimit, signal, emit }) {
67
63
  const wanted = settings.judge && verification.kept.length > 0;
68
64
  const affordable = spendLimit.mayCall();
69
65
  const judged = await judgeFindings(verification.kept, {
@@ -75,6 +71,7 @@ async function judge(verification, { reconciled, nothingReviewed }, { options, s
75
71
  enabled: wanted && affordable,
76
72
  keepDropped: settings.ultra,
77
73
  carried: stillOpen(reconciled),
74
+ ...(settled ? { settled } : {}),
78
75
  });
79
76
  if (wanted && !affordable) {
80
77
  judged.warnings.push(`spend limit of $${settings.maxCostUsd} reached: findings were not judged`);
@@ -0,0 +1,16 @@
1
+ import type { Finding } from "../domain.js";
2
+ import type { MatrixCell } from "../matrix/matrix.js";
3
+ import { type EarlyVerification } from "../verify/early.js";
4
+ import type { VerifyOptions } from "../verify/verify.js";
5
+ import type { StageContext } from "./execute-stage.js";
6
+ interface EarlyResult {
7
+ verification: EarlyVerification;
8
+ settled: ReadonlySet<string>;
9
+ }
10
+ export interface EarlyCheck {
11
+ readonly submitted: ReadonlySet<string>;
12
+ taskEnded(cell: MatrixCell, findings: readonly Finding[]): void;
13
+ result(): Promise<EarlyResult>;
14
+ }
15
+ export declare function earlyCheck(cells: readonly MatrixCell[], verify: VerifyOptions, { settings, plan, emit }: StageContext): EarlyCheck | undefined;
16
+ export {};
@@ -0,0 +1,95 @@
1
+ import { protectedFinding } from "../judge/judge.js";
2
+ import { staysDismissed } from "../rereview/reconcile.js";
3
+ import { earlyVerifier } from "../verify/early.js";
4
+ import { dedupeFindings } from "./findings.js";
5
+ // Undefined when the run does not verify.
6
+ export function earlyCheck(cells, verify, { settings, plan, emit }) {
7
+ if (!settings.verify)
8
+ return undefined;
9
+ const settled = new Set();
10
+ const verifier = earlyVerifier(verify, (file, verified) => {
11
+ const now = settle(verified, settings.showPreExisting);
12
+ for (const f of now)
13
+ settled.add(f.id);
14
+ emit({
15
+ type: "findings_verified",
16
+ file,
17
+ kept: verified.kept,
18
+ refuted: verified.refuted.map((r) => r.finding.id),
19
+ settled: now.map((f) => f.id),
20
+ });
21
+ });
22
+ if (!verifier)
23
+ return undefined;
24
+ const reportable = keptByPeople(plan.prior.review, plan.memory);
25
+ const order = new Map(cells.map((cell, index) => [cell.taskId, index]));
26
+ const open = openTasks(cells);
27
+ const found = new Map();
28
+ return {
29
+ submitted: verifier.submitted,
30
+ taskEnded(cell, findings) {
31
+ const at = order.get(cell.taskId) ?? cells.length;
32
+ for (const finding of findings) {
33
+ // A file checked already keeps its answer: a finding that names it
34
+ // later waits for Verify.
35
+ if (open.has(finding.file)) {
36
+ found.set(finding.file, [...(found.get(finding.file) ?? []), { at, finding }]);
37
+ }
38
+ }
39
+ for (const { newPath } of cell.bundle.files) {
40
+ const tasks = open.get(newPath);
41
+ tasks?.delete(cell.taskId);
42
+ if (tasks?.size !== 0)
43
+ continue;
44
+ open.delete(newPath);
45
+ // In the tasks' order, as Verify would see them.
46
+ const group = dedupeFindings((found.get(newPath) ?? []).sort((a, b) => a.at - b.at).map((f) => f.finding)).filter(reportable);
47
+ if (group.length > 0)
48
+ verifier.verify(newPath, group);
49
+ }
50
+ },
51
+ result: async () => ({ verification: await verifier.result(), settled }),
52
+ };
53
+ }
54
+ // The tasks still to end, by file they review.
55
+ function openTasks(cells) {
56
+ const open = new Map();
57
+ for (const cell of cells) {
58
+ for (const { newPath } of cell.bundle.files) {
59
+ open.set(newPath, (open.get(newPath) ?? new Set()).add(cell.taskId));
60
+ }
61
+ }
62
+ return open;
63
+ }
64
+ // What memory and a person's dismissal leave of the findings (filter-stage.ts
65
+ // applies both to the whole run); neither is worth a verifier call.
66
+ function keptByPeople(prior, memory) {
67
+ const accepted = new Set(memory.map((e) => e.fingerprint));
68
+ const before = new Map(prior?.findings.map((f) => [f.fingerprint, f]));
69
+ return (finding) => {
70
+ if (accepted.has(finding.fingerprint))
71
+ return false;
72
+ const old = before.get(finding.fingerprint);
73
+ return !(old && staysDismissed(finding, old));
74
+ };
75
+ }
76
+ // The judge can neither drop nor downgrade a confirmed critical finding, but
77
+ // it may merge two that say the same thing; of findings on overlapping lines
78
+ // only the first is settled, and the others wait for it.
79
+ function settle(verified, showPreExisting) {
80
+ const settled = [];
81
+ for (const finding of verified.kept) {
82
+ if (!protectedFinding(finding))
83
+ continue;
84
+ if (finding.preExisting && !showPreExisting)
85
+ continue;
86
+ if (!settled.some((other) => overlap(other, finding)))
87
+ settled.push(finding);
88
+ }
89
+ return settled;
90
+ }
91
+ function overlap(a, b) {
92
+ if (!a.lineRange || !b.lineRange)
93
+ return true;
94
+ return a.lineRange.start <= b.lineRange.end && b.lineRange.start <= a.lineRange.end;
95
+ }
@@ -3,6 +3,8 @@ import type { Usage } from "../contracts.js";
3
3
  import { type ReviewMatrix } from "../matrix/matrix.js";
4
4
  import type { ReviewEvent } from "../report/report.js";
5
5
  import type { ReviewerDefinition } from "../review/reviewer.js";
6
+ import type { VerifyOptions } from "../verify/verify.js";
7
+ import { type EarlyCheck } from "./early-check.js";
6
8
  import { type JobResult } from "./execute.js";
7
9
  import { type ReviewHooks, type ReviewOptions, type RunSettings } from "./options.js";
8
10
  import type { ReviewPlan } from "./plan.js";
@@ -21,5 +23,7 @@ export interface ExecuteStage {
21
23
  relocations: readonly Usage[];
22
24
  usage(): Usage[];
23
25
  warnings: string[];
26
+ early?: EarlyCheck;
24
27
  }
25
28
  export declare function executeStage(reviewers: readonly ReviewerDefinition[], context: StageContext): Promise<ExecuteStage>;
29
+ export declare function verifyOptions({ options, settings, plan, spendLimit, signal, }: StageContext): VerifyOptions;
@@ -4,6 +4,7 @@ import { emptyUsage } from "../agent/usage.js";
4
4
  import { runtimeRelocator } from "../anchor/relocate.js";
5
5
  import { DEFAULT_MAX_TASKS, planTasks, } from "../matrix/matrix.js";
6
6
  import { securityReviewed } from "../sarif/evidence.js";
7
+ import { earlyCheck } from "./early-check.js";
7
8
  import { prepareJob, reuseJob, runJob } from "./execute.js";
8
9
  import { guidelinesShown, } from "./options.js";
9
10
  import { reusePool } from "./resume.js";
@@ -33,7 +34,7 @@ export async function executeStage(reviewers, context) {
33
34
  execute.reuse = { pool, runId: resume.runId };
34
35
  const notStarted = new Set();
35
36
  let unaffordable = 0;
36
- const results = await mapWithConcurrency(matrix.cells, settings.concurrency, async (cell) => {
37
+ const runCell = async (cell) => {
37
38
  // Once the run is cancelled or timed out, remaining cells are not started.
38
39
  if (context.signal.aborted) {
39
40
  notStarted.add(cell.taskId);
@@ -49,6 +50,12 @@ export async function executeStage(reviewers, context) {
49
50
  return skipCell(cell, `spend limit of $${settings.maxCostUsd} reached`, emit);
50
51
  }
51
52
  return runJob(cell, plan, execute, prepared);
53
+ };
54
+ const early = earlyCheck(matrix.cells, verifyOptions(context), context);
55
+ const results = await mapWithConcurrency(matrix.cells, settings.concurrency, async (cell) => {
56
+ const result = await runCell(cell);
57
+ early?.taskEnded(cell, result.findings);
58
+ return result;
52
59
  });
53
60
  if (unaffordable > 0) {
54
61
  warnings.push(`spend limit of $${settings.maxCostUsd} reached: ${unaffordable} review task(s) did not start; their files are reported as not reviewed`);
@@ -63,6 +70,19 @@ export async function executeStage(reviewers, context) {
63
70
  relocations,
64
71
  usage: () => [...results.map((r) => r.usage), ...relocations],
65
72
  warnings,
73
+ ...(early ? { early } : {}),
74
+ };
75
+ }
76
+ // One for the calls made while tasks run and the ones Verify makes after.
77
+ export function verifyOptions({ options, settings, plan, spendLimit, signal, }) {
78
+ return {
79
+ runtime: options.runtime,
80
+ diffs: plan.selected,
81
+ context: plan.context,
82
+ signal,
83
+ concurrency: settings.concurrency,
84
+ spendLimit,
85
+ call: roleCall("verifier", options),
66
86
  };
67
87
  }
68
88
  function executeOptions({ options, settings, spendLimit, signal, emit }, relocations) {
@@ -14,7 +14,7 @@ export async function filterStage(executed, prior, { options, plan, emit }) {
14
14
  ? await importSarif(options.sarif, plan, emit)
15
15
  : { findings: [], outcomes: [], warnings: [] };
16
16
  const { results } = executed;
17
- const found = dedupeFindings([...results.flatMap((r) => r.findings), ...imported.findings]);
17
+ const found = dedupeFindings([...results.flatMap((r) => r.findings), ...imported.findings], executed.early?.submitted);
18
18
  const coverage = coverageOf(plan.decisions, results, plan.unchanged, executed.matrix.limited ?? [], executed.notStarted);
19
19
  emit({ type: "coverage_settled", coverage });
20
20
  const remembered = applyMemory(found, plan.memory);
@@ -2,4 +2,4 @@ import type { Anchor } from "../anchor/anchor.js";
2
2
  import type { Finding, FindingProvenance, ReportedFinding } from "../domain.js";
3
3
  export declare function fingerprint(category: string, file: string, existingCode: string): string;
4
4
  export declare function toFinding(reported: ReportedFinding, reviewer: string, provenance: FindingProvenance, anchor: Anchor, content?: string): Finding;
5
- export declare function dedupeFindings(findings: readonly Finding[]): Finding[];
5
+ export declare function dedupeFindings(findings: readonly Finding[], checked?: ReadonlySet<string>): Finding[];
@@ -32,12 +32,16 @@ export function toFinding(reported, reviewer, provenance, anchor, content) {
32
32
  return finding;
33
33
  }
34
34
  // The most severe copy wins whole: its title and explanation describe the
35
- // severity it carries.
36
- export function dedupeFindings(findings) {
35
+ // severity it carries. Among equally severe copies the one verification
36
+ // already has (`checked`, by id) wins, so it is not checked twice.
37
+ export function dedupeFindings(findings, checked = new Set()) {
37
38
  const byFingerprint = new Map();
38
39
  for (const finding of findings) {
39
40
  const existing = byFingerprint.get(finding.fingerprint);
40
- if (!existing || SEVERITY_RANK[finding.severity] > SEVERITY_RANK[existing.severity]) {
41
+ const rank = existing && SEVERITY_RANK[finding.severity] - SEVERITY_RANK[existing.severity];
42
+ if (rank === undefined ||
43
+ rank > 0 ||
44
+ (rank === 0 && checked.has(finding.id) && !checked.has(existing?.id ?? ""))) {
41
45
  byFingerprint.set(finding.fingerprint, finding);
42
46
  }
43
47
  }
@@ -0,0 +1,59 @@
1
+ import { type AgentCallSettings } from "../agent/settings.js";
2
+ import { type SpendLimit } from "../agent/spend-limit.js";
3
+ import type { AgentRuntime, ReviewContext, SyntaxChecker, Usage } from "../contracts.js";
4
+ import type { FileDiff, FindingFix, Severity } from "../domain.js";
5
+ import type { FixRejection } from "../fix/check.js";
6
+ import type { VcsAdapter } from "../vcs.js";
7
+ import type { ReviewOptions } from "./options.js";
8
+ export interface StoredFinding {
9
+ fingerprint: string;
10
+ reviewer: string;
11
+ severity: Severity;
12
+ category: string;
13
+ file: string;
14
+ title: string;
15
+ body: string;
16
+ suggestion?: string;
17
+ existingCode?: string;
18
+ lowConfidence?: boolean;
19
+ altered?: boolean;
20
+ }
21
+ type FixFindingOutcome = "proposed" | "rejected" | "not_fixable" | "stale" | "head_moved";
22
+ type FixFindingReason = FixRejection | "not_candidate";
23
+ export interface FixedFinding {
24
+ headSha: string;
25
+ outcome: FixFindingOutcome;
26
+ fix?: FindingFix;
27
+ reason?: FixFindingReason;
28
+ warnings: string[];
29
+ }
30
+ interface FixFindingOptions extends Pick<ReviewOptions, "effort" | "roles"> {
31
+ finding: StoredFinding;
32
+ vcs: VcsAdapter;
33
+ runtime: AgentRuntime;
34
+ syntax: SyntaxChecker;
35
+ expectedHead?: string;
36
+ maxCostUsd?: number;
37
+ signal: AbortSignal;
38
+ onUsage: (usage: Usage) => void;
39
+ }
40
+ export declare function fixFinding(options: FixFindingOptions): Promise<FixedFinding>;
41
+ interface HeadFixOptions {
42
+ runtime: AgentRuntime;
43
+ syntax: SyntaxChecker;
44
+ diffs: readonly FileDiff[];
45
+ context: ReviewContext;
46
+ spendLimit: Pick<SpendLimit, "mayCall" | "charge">;
47
+ call: AgentCallSettings;
48
+ signal: AbortSignal;
49
+ onUsage: (usage: Usage) => void;
50
+ }
51
+ type HeadFix = {
52
+ fix: FindingFix;
53
+ warnings: string[];
54
+ } | {
55
+ reason: FixFindingReason;
56
+ warnings: string[];
57
+ };
58
+ export declare function fixAtHead(finding: StoredFinding, options: HeadFixOptions): Promise<HeadFix>;
59
+ export {};
@@ -0,0 +1,123 @@
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 { matchInContent, matchInHunks } from "../anchor/match.js";
5
+ import { quoteSignature } from "../anchor/quote.js";
6
+ import { OcraError } from "../errors.js";
7
+ import { proposeFixes } from "../fix/propose.js";
8
+ import { MAX_FIX_SPAN_LINES } from "../fix/select.js";
9
+ import { reviewContext } from "./context.js";
10
+ const OUTCOME_OF = {
11
+ declined: "not_fixable",
12
+ no_parser: "not_fixable",
13
+ not_candidate: "not_fixable",
14
+ stale: "stale",
15
+ failed: "rejected",
16
+ unchanged: "rejected",
17
+ unsafe: "rejected",
18
+ too_large: "rejected",
19
+ syntax: "rejected",
20
+ };
21
+ // A checked fix for one stored finding (ADR-0077): the finding is anchored
22
+ // again at the head by the review's rules, and a fix is asked only for one
23
+ // the fix stage would ask for (fixCandidates), whether or not it had a fix.
24
+ export async function fixFinding(options) {
25
+ const { vcs, finding } = options;
26
+ if (!oneShot(options.runtime, () => { })) {
27
+ throw new OcraError("RUNTIME_START_FAILED", `the ${options.runtime.name} runtime makes no plain completions, which ocra fix needs`);
28
+ }
29
+ const { headSha } = await vcs.getChangeRequest();
30
+ if (options.expectedHead !== undefined && options.expectedHead !== headSha) {
31
+ return { headSha, outcome: "head_moved", warnings: [] };
32
+ }
33
+ const diffs = await vcs.getDiff();
34
+ const fixed = await fixAtHead(finding, {
35
+ runtime: options.runtime,
36
+ syntax: options.syntax,
37
+ diffs,
38
+ context: reviewContext(vcs, diffs),
39
+ spendLimit: spendLimit(options.maxCostUsd),
40
+ call: roleCall("fixer", options),
41
+ signal: options.signal,
42
+ onUsage: options.onUsage,
43
+ });
44
+ if ("fix" in fixed)
45
+ return { headSha, outcome: "proposed", ...fixed };
46
+ return { headSha, outcome: OUTCOME_OF[fixed.reason], ...fixed };
47
+ }
48
+ // The fix for one stored finding in a change already read: the finding is
49
+ // anchored again by its quote, asked for through proposeFixes and checked.
50
+ export async function fixAtHead(finding, options) {
51
+ const { diffs, context } = options;
52
+ if (finding.lowConfidence)
53
+ return { reason: "not_candidate", warnings: [] };
54
+ let content;
55
+ try {
56
+ content = await context.readFile(finding.file);
57
+ }
58
+ catch {
59
+ // The access policy refuses it: no review read it, and no fix will.
60
+ return { reason: "not_candidate", warnings: [] };
61
+ }
62
+ if (content === undefined)
63
+ return { reason: "stale", warnings: [] };
64
+ const located = locate(finding, diffs, content);
65
+ if (typeof located === "string")
66
+ return { reason: located, warnings: [] };
67
+ const lineRange = located.range;
68
+ const quote = quoteSignature(content, lineRange);
69
+ const candidate = {
70
+ id: finding.fingerprint,
71
+ fingerprint: finding.fingerprint,
72
+ reviewer: finding.reviewer,
73
+ category: finding.category,
74
+ severity: finding.severity,
75
+ file: finding.file,
76
+ existingCode: finding.existingCode ?? "",
77
+ title: finding.title,
78
+ body: finding.body,
79
+ ...(finding.suggestion ? { suggestion: finding.suggestion } : {}),
80
+ evidence: [],
81
+ lineRange,
82
+ ...(quote ? { quote } : {}),
83
+ provenance: { task: "fix" },
84
+ anchor: { method: "hunk", inDiff: true },
85
+ status: "new",
86
+ };
87
+ const result = await proposeFixes([candidate], {
88
+ runtime: options.runtime,
89
+ syntax: options.syntax,
90
+ diffs,
91
+ context,
92
+ signal: options.signal,
93
+ concurrency: 1,
94
+ maxFixes: 1,
95
+ spendLimit: options.spendLimit,
96
+ call: options.call,
97
+ });
98
+ for (const usage of result.usage)
99
+ options.onUsage(usage);
100
+ const fix = result.findings[0]?.fix;
101
+ if (fix)
102
+ return { fix, warnings: result.warnings };
103
+ return { reason: result.summary.rejected[0]?.reason ?? "failed", warnings: result.warnings };
104
+ }
105
+ // Where the finding's quote is at the head. Only a quote that fits one place
106
+ // in the change's hunks is a candidate, as anchoring by "hunk" is; a quote
107
+ // found nowhere in the file is stale, unless the stored text was altered.
108
+ function locate(finding, diffs, content) {
109
+ const code = finding.existingCode ?? "";
110
+ if (code.trim() === "")
111
+ return "not_candidate";
112
+ const own = diffs.find((d) => d.newPath === finding.file);
113
+ const inHunk = own ? matchInHunks(own, code) : undefined;
114
+ if (inHunk?.kind === "found") {
115
+ const { range } = inHunk;
116
+ return range.end - range.start < MAX_FIX_SPAN_LINES ? { range } : "not_candidate";
117
+ }
118
+ if (inHunk?.kind === "ambiguous")
119
+ return "not_candidate";
120
+ if (matchInContent(content, code).kind !== "none")
121
+ return "not_candidate";
122
+ return finding.altered ? "not_candidate" : "stale";
123
+ }
@@ -0,0 +1,43 @@
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";
4
+ import type { VcsAdapter } from "../vcs.js";
5
+ import { type StoredFinding } from "./fix-finding.js";
6
+ 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
+ }
29
+ interface MendOptions extends Pick<ReviewOptions, "effort" | "roles"> {
30
+ findings: readonly StoredFinding[];
31
+ vcs: VcsAdapter;
32
+ runtime: AgentRuntime;
33
+ syntax: SyntaxChecker;
34
+ level: MendLevel;
35
+ state?: MendState;
36
+ expectedHead?: string;
37
+ maxCostUsd?: number;
38
+ protectedPaths?: readonly string[];
39
+ signal: AbortSignal;
40
+ onUsage: (usage: Usage) => void;
41
+ }
42
+ export declare function mendRound(options: MendOptions): Promise<MendRound>;
43
+ export {};