@open-cr-agent/core 0.16.0 → 0.19.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 (61) 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/domain.d.ts +7 -0
  6. package/dist/index.d.ts +4 -1
  7. package/dist/index.js +4 -1
  8. package/dist/internal.d.ts +1 -0
  9. package/dist/internal.js +1 -0
  10. package/dist/judge/judge.d.ts +3 -1
  11. package/dist/judge/judge.js +8 -8
  12. package/dist/learn/draft.js +1 -1
  13. package/dist/matrix/matrix.js +44 -7
  14. package/dist/net/fetch-failure.d.ts +1 -0
  15. package/dist/net/fetch-failure.js +20 -0
  16. package/dist/pipeline/assemble-report.js +4 -0
  17. package/dist/pipeline/check-stage.d.ts +3 -2
  18. package/dist/pipeline/check-stage.js +12 -15
  19. package/dist/pipeline/early-check.d.ts +16 -0
  20. package/dist/pipeline/early-check.js +95 -0
  21. package/dist/pipeline/execute-stage.d.ts +4 -0
  22. package/dist/pipeline/execute-stage.js +21 -1
  23. package/dist/pipeline/filter-stage.js +1 -1
  24. package/dist/pipeline/findings.d.ts +1 -1
  25. package/dist/pipeline/findings.js +7 -3
  26. package/dist/pipeline/fix-finding.d.ts +39 -0
  27. package/dist/pipeline/fix-finding.js +113 -0
  28. package/dist/pipeline/options.d.ts +2 -0
  29. package/dist/pipeline/run.js +3 -2
  30. package/dist/pipeline/task-prompt.js +7 -1
  31. package/dist/pipeline/task.js +7 -0
  32. package/dist/plugin/types.d.ts +1 -0
  33. package/dist/report/inline.d.ts +37 -0
  34. package/dist/report/inline.js +67 -0
  35. package/dist/report/output-schema.d.ts +15 -0
  36. package/dist/report/output-schema.js +2 -0
  37. package/dist/report/output.js +7 -0
  38. package/dist/report/report.d.ts +8 -0
  39. package/dist/rereview/reconcile.d.ts +1 -0
  40. package/dist/rereview/reconcile.js +5 -1
  41. package/dist/review/prompt-text.d.ts +1 -1
  42. package/dist/review/prompt-text.js +1 -0
  43. package/dist/review/reviewer.d.ts +1 -1
  44. package/dist/review/reviewers/agents-md.js +4 -1
  45. package/dist/review/reviewers/correctness.js +5 -2
  46. package/dist/review/reviewers/docs.js +5 -2
  47. package/dist/review/reviewers/performance.js +6 -2
  48. package/dist/review/reviewers/security.js +6 -3
  49. package/dist/review/reviewers/writing.d.ts +1 -0
  50. package/dist/review/reviewers/writing.js +8 -0
  51. package/dist/runtime/attempt.d.ts +1 -0
  52. package/dist/runtime/attempt.js +4 -1
  53. package/dist/runtime/failback.js +3 -2
  54. package/dist/runtime/text-tools.d.ts +16 -0
  55. package/dist/runtime/text-tools.js +60 -0
  56. package/dist/runtime/tools.js +5 -1
  57. package/dist/verify/early.d.ts +22 -0
  58. package/dist/verify/early.js +79 -0
  59. package/dist/verify/verify.d.ts +13 -0
  60. package/dist/verify/verify.js +77 -64
  61. package/package.json +3 -3
@@ -19,6 +19,7 @@ export interface AttemptOutcome {
19
19
  usage: Usage;
20
20
  error?: AttemptError;
21
21
  unreadMessages?: number;
22
+ refusedFindings?: string[];
22
23
  }
23
24
  export interface WrapUpOutcome {
24
25
  findings: number;
@@ -36,7 +36,10 @@ export function attemptSummary(model, outcome) {
36
36
  const unread = outcome.unreadMessages
37
37
  ? `, ${outcome.unreadMessages} session message(s) not read (their findings and usage are missing)`
38
38
  : "";
39
- return `${model}: ${outcome.steps} step(s), ${toolSummary(outcome.toolCalls)}${resumed}${wrapUpSummary(outcome.wrappedUp)}, ${inputTokens} in / ${outputTokens} out / ${reasoningTokens} reasoning tokens, $${costUsd.toFixed(4)}${unread}`;
39
+ const refused = outcome.refusedFindings?.length
40
+ ? `, ${outcome.refusedFindings.length} finding(s) refused for their arguments and not sent again`
41
+ : "";
42
+ return `${model}: ${outcome.steps} step(s), ${toolSummary(outcome.toolCalls)}${resumed}${wrapUpSummary(outcome.wrappedUp)}, ${inputTokens} in / ${outputTokens} out / ${reasoningTokens} reasoning tokens, $${costUsd.toFixed(4)}${unread}${refused}`;
40
43
  }
41
44
  function wrapUpSummary(wrapUp) {
42
45
  if (!wrapUp)
@@ -60,7 +60,7 @@ export async function* withFailback(options) {
60
60
  // the run's limit: the pipeline decides what that stop means.
61
61
  if (!outcome.error) {
62
62
  health.recordSuccess(model);
63
- yield doneEvent(taskId, ended, outcome.wrappedUp);
63
+ yield doneEvent(taskId, ended, outcome);
64
64
  return;
65
65
  }
66
66
  // A cancelled attempt is neither finished nor the model's fault.
@@ -96,12 +96,13 @@ export async function* withFailback(options) {
96
96
  ...(quota ? { quota } : {}),
97
97
  };
98
98
  }
99
- function doneEvent(taskId, ended, wrappedUp) {
99
+ function doneEvent(taskId, ended, { wrappedUp, refusedFindings }) {
100
100
  return {
101
101
  type: "done",
102
102
  taskId,
103
103
  ...(ended === "step_cap" || ended === "stopped_early" ? { ended } : {}),
104
104
  ...(wrappedUp ? { wrapUp: { findings: wrappedUp.findings } } : {}),
105
+ ...(refusedFindings?.length ? { refusedFindings } : {}),
105
106
  };
106
107
  }
107
108
  function rateLimited(model, pauseMs) {
@@ -0,0 +1,16 @@
1
+ import type { ToolDefinition } from "../plugin/types.js";
2
+ import { type PromptText } from "../review/prompt-text.js";
3
+ export interface TextToolCall {
4
+ name: string;
5
+ input: unknown;
6
+ malformed?: true;
7
+ }
8
+ export declare function textToolInstructions(tools: readonly ToolDefinition[]): string;
9
+ export declare function parseTextToolCalls(answer: string): {
10
+ text: string;
11
+ calls: TextToolCall[];
12
+ };
13
+ export declare function textToolResults(outputs: readonly {
14
+ name: string;
15
+ output: string;
16
+ }[]): PromptText;
@@ -0,0 +1,60 @@
1
+ import { z } from "zod";
2
+ import { data, join, section } from "../review/prompt-text.js";
3
+ // Tool calls as text, for a model endpoint that takes no `tools` parameter
4
+ // (ADR-0070): the tools are described in the system prompt, the model writes
5
+ // each call as a block, and the results come back in the next message. The
6
+ // call's form is the one open models are trained on (Hermes, Qwen).
7
+ const CALL = /<tool_call>\s*([\s\S]*?)\s*(?:<\/tool_call>|$)/g;
8
+ const callSchema = z.object({
9
+ name: z.string().min(1),
10
+ // Some models write the arguments as a string of JSON, as the chat
11
+ // completions protocol does.
12
+ arguments: z.union([z.record(z.string(), z.unknown()), z.string()]).optional(),
13
+ });
14
+ // What the system prompt says about the tools, after the agent's own.
15
+ export function textToolInstructions(tools) {
16
+ const listed = tools.map((tool) => {
17
+ const { $schema: _, ...parameters } = z.toJSONSchema(tool.inputSchema);
18
+ return `- ${tool.name}: ${tool.description} Arguments: ${JSON.stringify(parameters)}`;
19
+ });
20
+ return `## Calling tools
21
+ To call a tool, write a block of exactly this form:
22
+ <tool_call>
23
+ {"name": "<tool name>", "arguments": {<its arguments as JSON>}}
24
+ </tool_call>
25
+ You may write several blocks in one answer. Write nothing after the last block: each call's result arrives in the next message, in an <ocra_tool_result> section. A tool is called only by such a block; describing a call in words does nothing.
26
+
27
+ The tools:
28
+ ${listed.join("\n")}`;
29
+ }
30
+ // The calls an answer makes and the text around them.
31
+ export function parseTextToolCalls(answer) {
32
+ const calls = [...answer.matchAll(CALL)].map((block) => toolCall(block[1] ?? ""));
33
+ return { text: answer.replace(CALL, "").trim(), calls };
34
+ }
35
+ function toolCall(body) {
36
+ let json;
37
+ try {
38
+ json = JSON.parse(body);
39
+ }
40
+ catch {
41
+ return { name: "unknown", input: undefined, malformed: true };
42
+ }
43
+ const parsed = callSchema.safeParse(json);
44
+ if (!parsed.success)
45
+ return { name: "unknown", input: undefined, malformed: true };
46
+ const { name, arguments: given = {} } = parsed.data;
47
+ if (typeof given !== "string")
48
+ return { name, input: given };
49
+ try {
50
+ return { name, input: JSON.parse(given || "{}") };
51
+ }
52
+ catch {
53
+ return { name, input: undefined, malformed: true };
54
+ }
55
+ }
56
+ // The message that answers a step's calls. A result is data: whatever a
57
+ // file holds, it cannot close its section or open another.
58
+ export function textToolResults(outputs) {
59
+ return join(outputs.map(({ name, output }) => section("tool_result", data(output), { tool: name })));
60
+ }
@@ -33,7 +33,11 @@ const reportFindingInput = z.object({
33
33
  title: z.string().min(1),
34
34
  body: z.string().min(1),
35
35
  suggestion: z.string().optional(),
36
- evidence: z.array(z.string()).optional(),
36
+ // Reviewers send one sentence of evidence as a bare string often enough
37
+ // that refusing it lost more than a quarter of the reports.
38
+ evidence: z
39
+ .preprocess((value) => (typeof value === "string" ? [value] : value), z.array(z.string()))
40
+ .optional(),
37
41
  });
38
42
  // Tool results carry repository text back to the model, so they are data
39
43
  // like every prompt section: they cannot form one of ocra's tags.
@@ -0,0 +1,22 @@
1
+ import type { Usage } from "../contracts.js";
2
+ import type { Finding, Verification } from "../domain.js";
3
+ import { type FileVerification, type VerificationResult, type VerifyOptions } from "./verify.js";
4
+ type Outcome = {
5
+ verification: Verification;
6
+ preExisting?: true;
7
+ } | {
8
+ refuted: string;
9
+ };
10
+ export interface EarlyVerification {
11
+ outcomes: ReadonlyMap<string, Outcome>;
12
+ usage: Usage[];
13
+ warnings: string[];
14
+ }
15
+ export interface EarlyVerifier {
16
+ readonly submitted: ReadonlySet<string>;
17
+ verify(file: string, group: readonly Finding[]): boolean;
18
+ result(): Promise<EarlyVerification>;
19
+ }
20
+ export declare function earlyVerifier(options: VerifyOptions, onFile: (file: string, verified: FileVerification) => void): EarlyVerifier | undefined;
21
+ export declare function verifyRemaining(findings: readonly Finding[], early: EarlyVerification | undefined, options: VerifyOptions): Promise<VerificationResult>;
22
+ export {};
@@ -0,0 +1,79 @@
1
+ import { oneShot } from "../agent/model-call.js";
2
+ import { limiter } from "../agent/pool.js";
3
+ import { missedOf, refutedFinding, verifyFile, verifyFindings, } from "./verify.js";
4
+ // Undefined when the runtime makes no plain completions.
5
+ export function earlyVerifier(options, onFile) {
6
+ const usage = [];
7
+ const ask = oneShot(options.runtime, (spent) => {
8
+ usage.push(spent);
9
+ options.spendLimit?.charge(spent);
10
+ });
11
+ if (!ask)
12
+ return undefined;
13
+ const limited = limiter(options.concurrency);
14
+ const submitted = new Set();
15
+ const outcomes = new Map();
16
+ const warnings = [];
17
+ const calls = [];
18
+ return {
19
+ submitted,
20
+ verify(file, group) {
21
+ if (options.spendLimit && !options.spendLimit.mayCall())
22
+ return false;
23
+ for (const finding of group)
24
+ submitted.add(finding.id);
25
+ calls.push(limited(() => verifyFile(file, group, options, ask)).then((verified) => {
26
+ for (const f of verified.kept) {
27
+ outcomes.set(f.id, {
28
+ verification: f.verification ?? "unchecked",
29
+ ...(f.preExisting ? { preExisting: true } : {}),
30
+ });
31
+ }
32
+ for (const { finding, reason } of verified.refuted) {
33
+ outcomes.set(finding.id, { refuted: reason });
34
+ }
35
+ if (verified.warning)
36
+ warnings.push(verified.warning);
37
+ onFile(file, verified);
38
+ }));
39
+ return true;
40
+ },
41
+ async result() {
42
+ await Promise.all(calls);
43
+ return { outcomes, usage, warnings };
44
+ },
45
+ };
46
+ }
47
+ // Verify for the findings the early calls did not answer, and both as one result.
48
+ export async function verifyRemaining(findings, early, options) {
49
+ if (!early)
50
+ return verifyFindings(findings, options);
51
+ const rest = await verifyFindings(findings.filter((f) => !early.outcomes.has(f.id)), options);
52
+ const later = new Map(rest.kept.map((f) => [f.id, f]));
53
+ const result = {
54
+ checked: rest.checked,
55
+ kept: [],
56
+ refuted: [...rest.refuted],
57
+ missed: [],
58
+ usage: [...early.usage, ...rest.usage],
59
+ warnings: [...early.warnings, ...rest.warnings],
60
+ };
61
+ for (const finding of findings) {
62
+ const outcome = early.outcomes.get(finding.id);
63
+ if (!outcome) {
64
+ const kept = later.get(finding.id);
65
+ if (kept)
66
+ result.kept.push(kept);
67
+ continue;
68
+ }
69
+ result.checked += 1;
70
+ if ("refuted" in outcome) {
71
+ result.refuted.push(refutedFinding({ finding, reason: outcome.refuted }));
72
+ }
73
+ else {
74
+ result.kept.push({ ...finding, ...outcome });
75
+ }
76
+ }
77
+ result.missed = missedOf(result.kept);
78
+ return result;
79
+ }
@@ -1,3 +1,4 @@
1
+ import { type OneShot } from "../agent/model-call.js";
1
2
  import type { AgentCallSettings } from "../agent/settings.js";
2
3
  import type { SpendLimit } from "../agent/spend-limit.js";
3
4
  import type { AgentRuntime, ReviewContext, Usage } from "../contracts.js";
@@ -26,4 +27,16 @@ export interface VerifyOptions {
26
27
  call?: AgentCallSettings | undefined;
27
28
  }
28
29
  export declare function verifyFindings(findings: readonly Finding[], options: VerifyOptions): Promise<VerificationResult>;
30
+ export declare const missedOf: (kept: readonly Finding[]) => string[];
31
+ export declare const refutedFinding: ({ finding, reason }: Refutation) => RefutedFinding;
32
+ export interface Refutation {
33
+ finding: Finding;
34
+ reason: string;
35
+ }
36
+ export interface FileVerification {
37
+ kept: Finding[];
38
+ refuted: Refutation[];
39
+ warning?: string;
40
+ }
41
+ export declare function verifyFile(file: string, group: readonly Finding[], options: Pick<VerifyOptions, "diffs" | "context" | "signal" | "call">, ask: OneShot): Promise<FileVerification>;
29
42
  export declare function markUnchecked(findings: readonly Finding[]): Finding[];
@@ -25,83 +25,96 @@ export async function verifyFindings(findings, options) {
25
25
  result.missed = findings.map((f) => f.fingerprint);
26
26
  return result;
27
27
  }
28
- const byFile = new Map();
29
- for (const finding of findings) {
30
- byFile.set(finding.file, [...(byFile.get(finding.file) ?? []), finding]);
31
- }
32
28
  let unaffordable = 0;
33
- await mapWithConcurrency([...byFile], options.concurrency, async ([file, group]) => {
29
+ await mapWithConcurrency([...byFile(findings)], options.concurrency, async ([file, group]) => {
34
30
  if (options.spendLimit && !options.spendLimit.mayCall()) {
35
31
  unaffordable += group.length;
36
32
  result.kept.push(...markUnchecked(group));
37
33
  return;
38
34
  }
39
35
  result.checked += group.length;
40
- const refutedIndexes = new Map();
41
- const outcomes = new Map();
42
- const preExisting = new Set();
43
- try {
44
- const patch = options.diffs.find((d) => d.newPath === file)?.patch ?? "";
45
- const [content, related] = await Promise.all([
46
- options.context.readFile(file).catch(() => undefined),
47
- relatedCode(file, group, options.context),
48
- ]);
49
- const prompt = buildVerificationPrompt(file, group, patch, content === undefined ? undefined : fileExcerpt(content, group), related);
50
- const answer = await ask({
51
- tier: "standard",
52
- agent: "verifier",
53
- call: options.call,
54
- system: prompt.system,
55
- user: prompt.user,
56
- timeoutMs: VERIFY_TIMEOUT_MS,
57
- }, options.signal);
58
- const parsed = verificationResponseSchema.safeParse(parseJsonAnswer(answer));
59
- if (!parsed.success)
60
- throw new OcraError("RUNTIME_INVALID_OUTPUT", "the verifier returned an invalid response");
61
- for (const entry of parsed.data) {
62
- const { index } = entry;
63
- if (index < 0 || index >= group.length)
64
- continue;
65
- if (outcomes.has(index) || refutedIndexes.has(index))
66
- continue;
67
- if (entry.verdict === "refuted")
68
- refutedIndexes.set(index, entry.reason);
69
- else
70
- outcomes.set(index, entry.verdict);
71
- if (entry.verdict !== "refuted" && entry.origin === "pre_existing")
72
- preExisting.add(index);
73
- }
74
- }
75
- catch (error) {
76
- result.warnings.push(`verification of ${file} failed, keeping its findings: ${errorMessage(error)}`);
77
- }
78
- group.forEach((finding, i) => {
79
- const reason = refutedIndexes.get(i);
80
- if (reason === undefined) {
81
- result.kept.push({
82
- ...finding,
83
- verification: outcomes.get(i) ?? "unchecked",
84
- ...(preExisting.has(i) ? { preExisting: true } : {}),
85
- });
86
- }
87
- else {
88
- result.refuted.push({
89
- fingerprint: finding.fingerprint,
90
- file: finding.file,
91
- title: finding.title,
92
- reason,
93
- });
94
- }
95
- });
36
+ const verified = await verifyFile(file, group, options, ask);
37
+ result.kept.push(...verified.kept);
38
+ result.refuted.push(...verified.refuted.map(refutedFinding));
39
+ if (verified.warning)
40
+ result.warnings.push(verified.warning);
96
41
  });
97
- result.missed = result.kept
98
- .filter((f) => f.verification === "unchecked")
99
- .map((f) => f.fingerprint);
42
+ result.missed = missedOf(result.kept);
100
43
  if (unaffordable > 0) {
101
44
  result.warnings.push(`spend limit reached: ${unaffordable} finding(s) were not verified and cannot block`);
102
45
  }
103
46
  return result;
104
47
  }
48
+ function byFile(findings) {
49
+ const groups = new Map();
50
+ for (const finding of findings) {
51
+ groups.set(finding.file, [...(groups.get(finding.file) ?? []), finding]);
52
+ }
53
+ return groups;
54
+ }
55
+ export const missedOf = (kept) => kept.filter((f) => f.verification === "unchecked").map((f) => f.fingerprint);
56
+ export const refutedFinding = ({ finding, reason }) => ({
57
+ fingerprint: finding.fingerprint,
58
+ file: finding.file,
59
+ title: finding.title,
60
+ reason,
61
+ });
62
+ // One call for one file's findings. Never throws: a failure keeps them.
63
+ export async function verifyFile(file, group, options, ask) {
64
+ const verified = { kept: [], refuted: [] };
65
+ const refutedIndexes = new Map();
66
+ const outcomes = new Map();
67
+ const preExisting = new Set();
68
+ try {
69
+ const patch = options.diffs.find((d) => d.newPath === file)?.patch ?? "";
70
+ const [content, related] = await Promise.all([
71
+ options.context.readFile(file).catch(() => undefined),
72
+ relatedCode(file, group, options.context),
73
+ ]);
74
+ const prompt = buildVerificationPrompt(file, group, patch, content === undefined ? undefined : fileExcerpt(content, group), related);
75
+ const answer = await ask({
76
+ tier: "standard",
77
+ agent: "verifier",
78
+ call: options.call,
79
+ system: prompt.system,
80
+ user: prompt.user,
81
+ timeoutMs: VERIFY_TIMEOUT_MS,
82
+ }, options.signal);
83
+ const parsed = verificationResponseSchema.safeParse(parseJsonAnswer(answer));
84
+ if (!parsed.success)
85
+ throw new OcraError("RUNTIME_INVALID_OUTPUT", "the verifier returned an invalid response");
86
+ for (const entry of parsed.data) {
87
+ const { index } = entry;
88
+ if (index < 0 || index >= group.length)
89
+ continue;
90
+ if (outcomes.has(index) || refutedIndexes.has(index))
91
+ continue;
92
+ if (entry.verdict === "refuted")
93
+ refutedIndexes.set(index, entry.reason);
94
+ else
95
+ outcomes.set(index, entry.verdict);
96
+ if (entry.verdict !== "refuted" && entry.origin === "pre_existing")
97
+ preExisting.add(index);
98
+ }
99
+ }
100
+ catch (error) {
101
+ verified.warning = `verification of ${file} failed, keeping its findings: ${errorMessage(error)}`;
102
+ }
103
+ group.forEach((finding, i) => {
104
+ const reason = refutedIndexes.get(i);
105
+ if (reason === undefined) {
106
+ verified.kept.push({
107
+ ...finding,
108
+ verification: outcomes.get(i) ?? "unchecked",
109
+ ...(preExisting.has(i) ? { preExisting: true } : {}),
110
+ });
111
+ }
112
+ else {
113
+ verified.refuted.push({ finding, reason });
114
+ }
115
+ });
116
+ return verified;
117
+ }
105
118
  export function markUnchecked(findings) {
106
119
  return findings.map((f) => ({ ...f, verification: "unchecked" }));
107
120
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-cr-agent/core",
3
- "version": "0.16.0",
3
+ "version": "0.19.0",
4
4
  "description": "Domain types, review pipeline stages and plugin contracts for Open-CR-Agent",
5
5
  "keywords": [
6
6
  "code-review",
@@ -12,10 +12,10 @@
12
12
  "homepage": "https://ocracloud.com",
13
13
  "repository": {
14
14
  "type": "git",
15
- "url": "git+https://github.com/jma49/Open-CR-Agent.git",
15
+ "url": "git+https://github.com/ocrahq/Open-CR-Agent.git",
16
16
  "directory": "packages/core"
17
17
  },
18
- "bugs": "https://github.com/jma49/Open-CR-Agent/issues",
18
+ "bugs": "https://github.com/ocrahq/Open-CR-Agent/issues",
19
19
  "engines": {
20
20
  "node": ">=22.19"
21
21
  },