@open-cr-agent/core 0.7.0 → 0.9.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 (101) hide show
  1. package/dist/agent/model-call.d.ts +13 -0
  2. package/dist/agent/model-call.js +22 -0
  3. package/dist/agent/settings.d.ts +9 -4
  4. package/dist/agent/settings.js +20 -7
  5. package/dist/agent/spend-limit.d.ts +18 -0
  6. package/dist/agent/spend-limit.js +53 -0
  7. package/dist/anchor/relocate.d.ts +1 -1
  8. package/dist/anchor/relocate.js +8 -14
  9. package/dist/bundle/runtime-grouper.d.ts +1 -1
  10. package/dist/bundle/runtime-grouper.js +8 -14
  11. package/dist/contracts.d.ts +27 -0
  12. package/dist/contracts.js +10 -0
  13. package/dist/domain.d.ts +7 -0
  14. package/dist/domain.js +2 -0
  15. package/dist/index.d.ts +8 -6
  16. package/dist/index.js +4 -4
  17. package/dist/internal.d.ts +7 -3
  18. package/dist/internal.js +7 -3
  19. package/dist/judge/judge.d.ts +1 -1
  20. package/dist/judge/judge.js +10 -13
  21. package/dist/judge/prompt.d.ts +1 -1
  22. package/dist/judge/prompt.js +10 -1
  23. package/dist/judge/verdict.d.ts +2 -1
  24. package/dist/judge/verdict.js +4 -2
  25. package/dist/knowledge/learning.d.ts +21 -0
  26. package/dist/knowledge/learning.js +1 -0
  27. package/dist/knowledge/select.d.ts +15 -0
  28. package/dist/knowledge/select.js +175 -0
  29. package/dist/learn/draft.d.ts +21 -0
  30. package/dist/learn/draft.js +123 -0
  31. package/dist/{pipeline → matrix}/matrix.d.ts +1 -2
  32. package/dist/{pipeline → matrix}/matrix.js +1 -1
  33. package/dist/pipeline/assemble-report.d.ts +0 -6
  34. package/dist/pipeline/assemble-report.js +33 -20
  35. package/dist/pipeline/check-stage.js +31 -11
  36. package/dist/pipeline/context.d.ts +2 -1
  37. package/dist/pipeline/context.js +19 -3
  38. package/dist/pipeline/coverage.d.ts +1 -1
  39. package/dist/pipeline/execute-stage.d.ts +5 -5
  40. package/dist/pipeline/execute-stage.js +21 -26
  41. package/dist/pipeline/execute.d.ts +4 -5
  42. package/dist/pipeline/execute.js +35 -51
  43. package/dist/pipeline/filter-stage.js +2 -0
  44. package/dist/pipeline/imports.js +2 -16
  45. package/dist/pipeline/options.d.ts +20 -1
  46. package/dist/pipeline/options.js +31 -0
  47. package/dist/pipeline/plan-output.d.ts +7 -0
  48. package/dist/pipeline/plan-output.js +9 -1
  49. package/dist/pipeline/plan.d.ts +14 -8
  50. package/dist/pipeline/plan.js +58 -8
  51. package/dist/pipeline/preview.d.ts +5 -4
  52. package/dist/pipeline/preview.js +18 -27
  53. package/dist/pipeline/run.js +18 -44
  54. package/dist/pipeline/task-prompt.d.ts +13 -0
  55. package/dist/pipeline/task-prompt.js +43 -0
  56. package/dist/pipeline/task.d.ts +3 -0
  57. package/dist/pipeline/task.js +3 -1
  58. package/dist/report/output-schema.d.ts +30 -0
  59. package/dist/report/output-schema.js +24 -2
  60. package/dist/report/output.js +24 -0
  61. package/dist/report/report.d.ts +32 -2
  62. package/dist/report/report.js +29 -0
  63. package/dist/review/impact.d.ts +20 -4
  64. package/dist/review/impact.js +153 -28
  65. package/dist/review/plan-phase.d.ts +1 -1
  66. package/dist/review/plan-phase.js +13 -12
  67. package/dist/review/prompt-text.d.ts +1 -1
  68. package/dist/review/prompt-text.js +82 -20
  69. package/dist/review/prompt.d.ts +6 -0
  70. package/dist/review/prompt.js +57 -2
  71. package/dist/review/tools.d.ts +1 -0
  72. package/dist/review/tools.js +1 -0
  73. package/dist/runtime/attempt.d.ts +12 -0
  74. package/dist/runtime/attempt.js +21 -1
  75. package/dist/runtime/chain-runner.d.ts +2 -2
  76. package/dist/runtime/failback.d.ts +2 -2
  77. package/dist/runtime/failback.js +29 -12
  78. package/dist/runtime/tools.js +11 -0
  79. package/dist/runtime/wrap-up.d.ts +6 -0
  80. package/dist/runtime/wrap-up.js +27 -0
  81. package/dist/sarif/candidates.d.ts +3 -2
  82. package/dist/sarif/candidates.js +2 -0
  83. package/dist/sarif/evidence.d.ts +35 -0
  84. package/dist/sarif/evidence.js +128 -0
  85. package/dist/sarif/schema.d.ts +18 -0
  86. package/dist/sarif/schema.js +8 -0
  87. package/dist/select/patterns.d.ts +1 -0
  88. package/dist/select/patterns.js +46 -0
  89. package/dist/select/select.d.ts +1 -0
  90. package/dist/select/select.js +18 -1
  91. package/dist/session/resume-read.js +3 -0
  92. package/dist/session/seal.js +5 -0
  93. package/dist/verify/prompt.d.ts +6 -2
  94. package/dist/verify/prompt.js +13 -4
  95. package/dist/verify/related.d.ts +3 -0
  96. package/dist/verify/related.js +88 -0
  97. package/dist/verify/verify.d.ts +3 -3
  98. package/dist/verify/verify.js +27 -19
  99. package/package.json +3 -3
  100. package/dist/agent/budget.d.ts +0 -12
  101. package/dist/agent/budget.js +0 -27
@@ -13,7 +13,8 @@ const WINDOWS = process.platform === "win32";
13
13
  // nothing outside the repository, whatever a prompt injection asks for.
14
14
  // Reads are memoized: the revision under review does not change during a run,
15
15
  // and anchoring and every agent re-read the same files.
16
- export function reviewContext(vcs, diffs) {
16
+ export function reviewContext(vcs, diffs, learnings = []) {
17
+ const byId = new Map(learnings.map((l) => [l.id, l]));
17
18
  const reads = new Map();
18
19
  const searches = new Map();
19
20
  // A file renamed away from a secret name still holds the secret, and
@@ -21,9 +22,19 @@ export function reviewContext(vcs, diffs) {
21
22
  const renamedSecrets = new Set(diffs
22
23
  .filter((d) => d.newPath !== d.oldPath && isSecretPath(d.oldPath))
23
24
  .map((d) => foldPath(d.newPath)));
25
+ // Every search match is checked: decided once per path.
26
+ const readable = new Map();
24
27
  const isReadable = (path) => {
25
- const normalized = normalize(path);
26
- return (normalized !== undefined && isAllowed(normalized) && !renamedSecrets.has(foldPath(normalized)));
28
+ let allowed = readable.get(path);
29
+ if (allowed === undefined) {
30
+ const normalized = normalize(path);
31
+ allowed =
32
+ normalized !== undefined &&
33
+ isAllowed(normalized) &&
34
+ !renamedSecrets.has(foldPath(normalized));
35
+ readable.set(path, allowed);
36
+ }
37
+ return allowed;
27
38
  };
28
39
  const allowedPath = (path) => {
29
40
  const normalized = normalize(path);
@@ -47,6 +58,11 @@ export function reviewContext(vcs, diffs) {
47
58
  const allowed = allowedPath(path);
48
59
  return diffs.find((d) => d.newPath === allowed || d.oldPath === allowed)?.patch;
49
60
  },
61
+ // From the trusted revision the run read them from, never the reviewed one.
62
+ readLearning(id) {
63
+ const learning = byId.get(id);
64
+ return learning && `${learning.title}\n\n${learning.body}`;
65
+ },
50
66
  // Agents in parallel often search for the same symbol.
51
67
  searchCode(literal) {
52
68
  let search = searches.get(literal);
@@ -1,5 +1,5 @@
1
+ import type { MatrixCell } from "../matrix/matrix.js";
1
2
  import type { CoverageEntry } from "../report/report.js";
2
3
  import type { FileDecision } from "../select/select.js";
3
4
  import type { JobResult } from "./execute.js";
4
- import type { MatrixCell } from "./matrix.js";
5
5
  export declare function coverageOf(decisions: readonly FileDecision[], results: readonly JobResult[], unchanged: ReadonlySet<string>, limited: readonly MatrixCell[], notStarted: ReadonlySet<string>): CoverageEntry[];
@@ -1,15 +1,16 @@
1
- import { type SpendTracker } from "../agent/budget.js";
1
+ import type { SpendLimit } from "../agent/spend-limit.js";
2
2
  import type { Usage } from "../contracts.js";
3
+ import { type ReviewMatrix } from "../matrix/matrix.js";
3
4
  import type { ReviewEvent } from "../report/report.js";
4
5
  import type { ReviewerDefinition } from "../review/reviewer.js";
5
6
  import { type JobResult } from "./execute.js";
6
- import { type ReviewMatrix } from "./matrix.js";
7
- import { type ReviewHooks, type ReviewOptions } from "./options.js";
7
+ import type { ReviewHooks, ReviewOptions, RunSettings } from "./options.js";
8
8
  import type { ReviewPlan } from "./plan.js";
9
9
  export interface StageContext {
10
10
  options: ReviewOptions & ReviewHooks;
11
+ settings: RunSettings;
11
12
  plan: ReviewPlan;
12
- budget: SpendTracker;
13
+ spendLimit: SpendLimit;
13
14
  signal: AbortSignal;
14
15
  emit: (event: ReviewEvent) => void;
15
16
  }
@@ -20,6 +21,5 @@ export interface ExecuteStage {
20
21
  relocations: readonly Usage[];
21
22
  usage(): Usage[];
22
23
  warnings: string[];
23
- reviewLimitReached(): boolean;
24
24
  }
25
25
  export declare function executeStage(reviewers: readonly ReviewerDefinition[], context: StageContext): Promise<ExecuteStage>;
@@ -1,37 +1,36 @@
1
- import { SpendLimitReached } from "../agent/budget.js";
2
1
  import { mapWithConcurrency } from "../agent/pool.js";
3
2
  import { roleCall } from "../agent/settings.js";
4
3
  import { emptyUsage } from "../agent/usage.js";
5
4
  import { runtimeRelocator } from "../anchor/relocate.js";
5
+ import { DEFAULT_MAX_TASKS, planTasks, } from "../matrix/matrix.js";
6
6
  import { jobKey, reuseJob, runJob } from "./execute.js";
7
- import { DEFAULT_MAX_TASKS, planTasks } from "./matrix.js";
8
- import { MAX_TIMER_MS, REVIEW_DEFAULTS } from "./options.js";
9
7
  import { reusePool } from "./resume.js";
10
8
  // One agent task per (bundle, reviewer) cell of the matrix, within the task
11
9
  // limit, the run's signal and the review share of the spend limit.
12
10
  export async function executeStage(reviewers, context) {
13
- const { options, plan, emit } = context;
11
+ const { options, settings, plan, emit } = context;
12
+ emit({ type: "stage_started", stage: "plan" });
14
13
  const matrix = planTasks(plan.bundles, reviewers, plan.tier, options.reviewerOverrides, {
15
- ultra: options.mode?.ultra === true,
16
- ...(options.limits?.maxTasks !== undefined ? { maxTasks: options.limits?.maxTasks } : {}),
14
+ ultra: settings.ultra,
15
+ ...(settings.maxTasks !== undefined ? { maxTasks: settings.maxTasks } : {}),
17
16
  hasGuidelines: Boolean(plan.guidelines?.trim()),
18
17
  });
19
18
  const warnings = [];
20
19
  const limited = matrix.skipped.filter((s) => s.reason === "task_limit").length;
21
20
  if (limited > 0) {
22
- warnings.push(`task limit of ${options.limits?.maxTasks ?? DEFAULT_MAX_TASKS} reached: ${limited} review task(s) skipped; their files are reported as not reviewed`);
21
+ warnings.push(`task limit of ${settings.maxTasks ?? DEFAULT_MAX_TASKS} reached: ${limited} review task(s) skipped; their files are reported as not reviewed`);
23
22
  }
24
23
  emit({ type: "matrix_planned", tasks: matrix.cells.length, skipped: matrix.skipped });
24
+ emit({ type: "stage_started", stage: "review" });
25
25
  const relocations = [];
26
- const spendLimit = new AbortController();
27
- const execute = executeOptions(context, relocations, spendLimit);
26
+ const execute = executeOptions(context, relocations);
28
27
  const resume = options.resume;
29
28
  const pool = reusePool(resume);
30
29
  if (resume)
31
30
  execute.reuse = { pool, runId: resume.runId };
32
31
  const notStarted = new Set();
33
32
  let unaffordable = 0;
34
- const results = await mapWithConcurrency(matrix.cells, options.limits?.concurrency ?? REVIEW_DEFAULTS.concurrency, async (cell) => {
33
+ const results = await mapWithConcurrency(matrix.cells, settings.concurrency, async (cell) => {
35
34
  // Once the run is cancelled or timed out, remaining cells are not started.
36
35
  if (context.signal.aborted) {
37
36
  notStarted.add(cell.taskId);
@@ -41,15 +40,15 @@ export async function executeStage(reviewers, context) {
41
40
  const reused = await reuseJob(cell, plan, execute, key);
42
41
  if (reused)
43
42
  return reused;
44
- if (context.budget.reviewExhausted()) {
43
+ if (!context.spendLimit.mayStartReview()) {
45
44
  notStarted.add(cell.taskId);
46
45
  unaffordable += 1;
47
- return skipCell(cell, `spend limit of $${options.limits?.maxCostUsd} reached`, emit);
46
+ return skipCell(cell, `spend limit of $${settings.maxCostUsd} reached`, emit);
48
47
  }
49
48
  return runJob(cell, plan, execute, key);
50
49
  });
51
50
  if (unaffordable > 0) {
52
- warnings.push(`spend limit of $${options.limits?.maxCostUsd} reached: ${unaffordable} review task(s) did not start; their files are reported as not reviewed`);
51
+ warnings.push(`spend limit of $${settings.maxCostUsd} reached: ${unaffordable} review task(s) did not start; their files are reported as not reviewed`);
53
52
  }
54
53
  if (resume)
55
54
  warnings.push(...resumeWarnings(resume.runId, pool.unused()));
@@ -61,35 +60,31 @@ export async function executeStage(reviewers, context) {
61
60
  relocations,
62
61
  usage: () => [...results.map((r) => r.usage), ...relocations],
63
62
  warnings,
64
- reviewLimitReached: () => spendLimit.signal.aborted || unaffordable > 0,
65
63
  };
66
64
  }
67
- function executeOptions({ options, budget, signal, emit }, relocations, spendLimit) {
65
+ function executeOptions({ options, settings, spendLimit, signal, emit }, relocations) {
68
66
  const relocator = relocatorOf(options, signal, (u) => {
69
67
  relocations.push(u);
70
- budget.add(u);
68
+ spendLimit.charge(u);
71
69
  });
72
70
  return {
73
71
  runtime: options.runtime,
74
- taskTimeoutMs: Math.min(options.limits?.taskTimeoutMs ?? REVIEW_DEFAULTS.taskTimeoutMs, MAX_TIMER_MS),
72
+ taskTimeoutMs: settings.taskTimeoutMs,
75
73
  abortGraceMs: options.abortGraceMs,
76
74
  // Past the spend limit a quote that does not match stays file-level.
77
75
  relocate: relocator &&
78
- (async (request) => (budget.exhausted() ? undefined : relocator(request))),
79
- ultra: options.mode?.ultra === true,
76
+ (async (request) => spendLimit.mayCall() ? relocator(request) : undefined),
77
+ ultra: settings.ultra,
78
+ symbols: options.symbols,
79
+ references: options.references,
80
80
  plans: new Map(),
81
81
  agents: options,
82
82
  keyInputs: keyInputs(options),
83
83
  emit,
84
84
  // Tasks report spend while they run, so the one that uses up the review
85
85
  // share stops every task still running, not only the ones not yet started.
86
- onUsage: (usage) => {
87
- budget.add(usage);
88
- if (budget.reviewExhausted() && !spendLimit.signal.aborted) {
89
- spendLimit.abort(new SpendLimitReached(options.limits?.maxCostUsd ?? 0));
90
- }
91
- },
92
- signal: AbortSignal.any([signal, spendLimit.signal]),
86
+ onUsage: (usage) => spendLimit.chargeReview(usage),
87
+ signal: AbortSignal.any([signal, spendLimit.reviewSignal]),
93
88
  };
94
89
  }
95
90
  // The caller's build and sampling: an earlier run made with another ocra or
@@ -1,10 +1,10 @@
1
1
  import { type AgentSettings } from "../agent/settings.js";
2
2
  import { type AnchorContext } from "../anchor/anchor.js";
3
- import type { AgentRuntime, Usage } from "../contracts.js";
3
+ import type { AgentRuntime, ReferenceIndex, SymbolExtractor, Usage } from "../contracts.js";
4
4
  import type { Finding } from "../domain.js";
5
+ import type { MatrixCell } from "../matrix/matrix.js";
5
6
  import type { ReviewEvent, TaskOutcome } from "../report/report.js";
6
7
  import { planBundle } from "../review/plan-phase.js";
7
- import type { MatrixCell } from "./matrix.js";
8
8
  import type { ReviewPlan } from "./plan.js";
9
9
  import type { ReusePool } from "./resume.js";
10
10
  export interface JobResult {
@@ -19,6 +19,8 @@ export interface ExecuteOptions {
19
19
  taskTimeoutMs: number;
20
20
  abortGraceMs?: number | undefined;
21
21
  relocate?: AnchorContext["relocate"] | undefined;
22
+ symbols?: SymbolExtractor | undefined;
23
+ references?: ReferenceIndex | undefined;
22
24
  plans?: Map<string, Promise<PlannedBundle>>;
23
25
  emit: (event: ReviewEvent) => void;
24
26
  onUsage?: ((usage: Usage) => void) | undefined;
@@ -31,9 +33,6 @@ export interface ExecuteOptions {
31
33
  keyInputs?: unknown;
32
34
  }
33
35
  type PlannedBundle = Awaited<ReturnType<typeof planBundle>>;
34
- export declare function isLargeBundle(files: readonly {
35
- patch: string;
36
- }[]): boolean;
37
36
  export declare function jobKey(job: MatrixCell, plan: ReviewPlan, options: ExecuteOptions): string;
38
37
  export declare function runJob(job: MatrixCell, plan: ReviewPlan, options: ExecuteOptions, key: string): Promise<JobResult>;
39
38
  export declare function reuseJob(job: MatrixCell, plan: ReviewPlan, options: ExecuteOptions, key: string): Promise<JobResult | undefined>;
@@ -1,35 +1,26 @@
1
- import { reviewerCall } from "../agent/settings.js";
1
+ import { chainOf, reviewerCall, } from "../agent/settings.js";
2
2
  import { addUsage, emptyUsage } from "../agent/usage.js";
3
3
  import { anchorFinding } from "../anchor/anchor.js";
4
- import { memoryFor } from "../memory/memory.js";
5
4
  import { findCallers } from "../review/impact.js";
6
5
  import { planBundle } from "../review/plan-phase.js";
7
6
  import { buildReviewPrompt } from "../review/prompt.js";
8
- import { resolveRules } from "../rules/resolve.js";
9
7
  import { toFinding } from "./findings.js";
10
8
  import { stableHash } from "./provenance.js";
11
9
  import { executeTask } from "./task.js";
12
- // In default mode only bundles large enough that a reviewer's 30 steps may
13
- // not cover them get a plan phase; --ultra plans every task.
14
- const PLAN_MIN_FILES = 5;
15
- const PLAN_MIN_PATCH_CHARS = 40_000;
16
- export function isLargeBundle(files) {
17
- const chars = files.reduce((sum, f) => sum + f.patch.length, 0);
18
- return files.length >= PLAN_MIN_FILES || chars >= PLAN_MIN_PATCH_CHARS;
19
- }
10
+ import { taskPrompt } from "./task-prompt.js";
20
11
  // The key of a cell's inputs (taskKey), under which its answer is reported
21
12
  // and an earlier run's answer is reused.
22
13
  export function jobKey(job, plan, options) {
23
14
  const call = reviewerCall(job.reviewer, options.agents ?? {});
24
- return taskKey(job, plan, buildReviewPrompt(promptInput(job, plan)), call, options);
15
+ return taskKey(job, plan, taskPrompt(job, plan, options.ultra === true).prompt, call, options);
25
16
  }
26
17
  // Runs one (bundle, reviewer) cell and anchors what it reports.
27
18
  export async function runJob(job, plan, options, key) {
28
19
  const { emit } = options;
29
20
  const files = job.bundle.files.map((f) => f.newPath);
30
21
  const call = reviewerCall(job.reviewer, options.agents ?? {});
31
- const input = promptInput(job, plan);
32
- const prepared = await preparePrompt(job, plan, options, call, input);
22
+ const task = taskPrompt(job, plan, options.ultra === true);
23
+ const prepared = await preparePrompt(job, plan, options, call, task);
33
24
  emit({
34
25
  type: "task_started",
35
26
  taskId: job.taskId,
@@ -75,6 +66,8 @@ export async function runJob(job, plan, options, key) {
75
66
  outcome.error = result.error;
76
67
  if (result.ended !== undefined)
77
68
  outcome.ended = result.ended;
69
+ if (result.wrapUp)
70
+ outcome.wrapUp = result.wrapUp;
78
71
  // A task cut off before it finished (ADR-0030) is reviewed again, not reused.
79
72
  if (result.status === "completed" && result.ended === undefined) {
80
73
  emit({ type: "task_reported", taskId: job.taskId, key, findings: result.findings });
@@ -82,32 +75,20 @@ export async function runJob(job, plan, options, key) {
82
75
  emit({ type: "task_finished", outcome });
83
76
  return { outcome, findings: anchored.findings, usage, warnings };
84
77
  }
85
- // The task's review prompt before a plan phase or callers are added.
86
- function promptInput(job, plan) {
87
- const files = job.bundle.files.map((f) => f.newPath);
88
- return {
89
- reviewer: job.reviewer,
90
- changeRequest: plan.changeRequest,
91
- changedFiles: plan.selected,
92
- bundle: job.bundle.files,
93
- rules: resolveRules(files, plan.repoRules, job.reviewer.rules),
94
- guidelines: plan.guidelines,
95
- accepted: memoryFor(files, plan.memory),
96
- };
97
- }
98
78
  // Everything a task's answer depends on, so an earlier answer is reused only
99
79
  // for the same question: the prompt (instructions, change, bundle, rules,
100
80
  // guidelines, memory), the commits (the code around the change, which the
101
81
  // reviewer reads but the prompt does not hold), the model chain and effort,
102
- // --ultra (which adds a plan phase and callers, both derived from the same
103
- // inputs), and the caller's build and sampling.
82
+ // --ultra (which adds a plan phase and callers; callers at the full tier,
83
+ // like the plan, are derived from the same inputs), and the caller's build
84
+ // and sampling.
104
85
  function taskKey(job, plan, prompt, call, options) {
105
86
  const { baseSha, headSha } = plan.changeRequest;
106
87
  return stableHash({
107
88
  prompt: { system: prompt.system, user: prompt.user },
108
89
  commits: { base: baseSha, head: headSha },
109
90
  tier: job.reviewer.modelTier,
110
- chain: call.models ?? options.agents?.models?.[job.reviewer.modelTier],
91
+ chain: chainOf(call, job.reviewer.modelTier, options.agents ?? {}),
111
92
  effort: call.effort,
112
93
  ultra: options.ultra === true,
113
94
  inputs: options.keyInputs,
@@ -148,21 +129,21 @@ export async function reuseJob(job, plan, options, key) {
148
129
  emit({ type: "task_finished", outcome });
149
130
  return { outcome, findings: anchored.findings, usage: emptyUsage(), warnings: anchored.warnings };
150
131
  }
151
- // The review prompt, with a plan phase and, under --ultra, the callers of
152
- // changed symbols.
153
- async function preparePrompt(job, plan, options, call, input) {
154
- if (!options.ultra && !isLargeBundle(job.bundle.files)) {
155
- return { prompt: buildReviewPrompt(input), usage: [], warnings: [] };
132
+ // The review prompt, with a plan phase and the callers of changed symbols
133
+ // when the task gets them.
134
+ async function preparePrompt(job, plan, options, call, task) {
135
+ const { planCall } = task;
136
+ const callers = task.callers ? await findCallers(job.bundle.files, plan.context, options) : [];
137
+ if (!planCall) {
138
+ const prompt = callers.length > 0 ? buildReviewPrompt({ ...task.input, callers }) : task.prompt;
139
+ return { prompt, usage: [], warnings: [] };
156
140
  }
157
- const callers = options.ultra ? await findCallers(job.bundle.files, plan.context) : [];
158
- const key = `${job.reviewer.id}\0${job.bundle.label}`;
159
- const shared = options.plans?.get(key);
160
- const planning = shared ??
161
- planBundle(options.runtime, job.reviewer, buildReviewPrompt({ ...input, forPlanning: true }), options.signal, call);
141
+ const shared = options.plans?.get(planCall.key);
142
+ const planning = shared ?? planBundle(options.runtime, job.reviewer, planCall.prompt(), options.signal, call);
162
143
  if (!shared)
163
- options.plans?.set(key, planning);
144
+ options.plans?.set(planCall.key, planning);
164
145
  const planned = await planning;
165
- const prompt = buildReviewPrompt({ ...input, callers, plan: planned.plan });
146
+ const prompt = buildReviewPrompt({ ...task.input, callers, plan: planned.plan });
166
147
  // The sample that made the call pays for it and reports its warning.
167
148
  if (shared)
168
149
  return { prompt, usage: [], warnings: [] };
@@ -179,26 +160,29 @@ async function anchorFindings(job, plan, options, reportedFindings) {
179
160
  };
180
161
  if (options.relocate)
181
162
  anchorContext.relocate = options.relocate;
182
- // A finding on a file outside the bundle belongs to the task that reviews
183
- // that file; keeping it would report the same issue once per bundle that
184
- // happened to read the file.
185
- const bundleFiles = new Set(job.bundle.files.map((f) => f.newPath));
163
+ // A finding on another file of the change is kept: a bug often shows where
164
+ // a changed caller meets a changed callee in another bundle, and dropping
165
+ // it lost the finding outright. A copy the task owning that file also
166
+ // reports shares its fingerprint, so the run keeps one (dedupeFindings).
167
+ // A file outside the change, or left out of an incremental review, is
168
+ // not under review.
169
+ const reviewed = new Set(plan.bundles.flatMap((b) => b.files.map((f) => f.newPath)));
186
170
  let outside = 0;
187
171
  for (const { reported, model } of reportedFindings) {
188
- // Relocating a quote on a file outside the bundle would pay for an
172
+ // Relocating a quote on a file outside the review would pay for an
189
173
  // answer the next check throws away.
190
- const context = bundleFiles.has(reported.file)
174
+ const context = reviewed.has(reported.file)
191
175
  ? anchorContext
192
176
  : { diffs: anchorContext.diffs, readNewFile: anchorContext.readNewFile };
193
177
  const anchor = await anchorFinding(reported, context);
194
178
  if (anchor.warning)
195
179
  warnings.push(`${job.taskId}: ${anchor.warning}`);
196
- if (!bundleFiles.has(anchor.file)) {
180
+ if (!reviewed.has(anchor.file)) {
197
181
  outside += 1;
198
182
  options.emit({
199
183
  type: "finding_dropped",
200
184
  taskId: job.taskId,
201
- reason: "outside_bundle",
185
+ reason: "outside_review",
202
186
  file: anchor.file,
203
187
  title: reported.title,
204
188
  });
@@ -213,7 +197,7 @@ async function anchorFindings(job, plan, options, reportedFindings) {
213
197
  options.emit({ type: "finding", taskId: job.taskId, finding });
214
198
  }
215
199
  if (outside > 0) {
216
- warnings.push(`${job.taskId}: dropped ${outside} finding(s) on files outside its bundle`);
200
+ warnings.push(`${job.taskId}: dropped ${outside} finding(s) on files outside the review`);
217
201
  }
218
202
  return { findings, warnings };
219
203
  }
@@ -9,12 +9,14 @@ import { importSarif } from "./imports.js";
9
9
  // paid for findings that will not be reported, and a person's dismissal
10
10
  // keeps a finding out of the verdict whatever the models say.
11
11
  export async function filterStage(executed, prior, { options, plan, emit }) {
12
+ emit({ type: "stage_started", stage: "filter" });
12
13
  const imported = options.sarif && options.sarif.length > 0
13
14
  ? await importSarif(options.sarif, plan, emit)
14
15
  : { findings: [], outcomes: [], warnings: [] };
15
16
  const { results } = executed;
16
17
  const found = dedupeFindings([...results.flatMap((r) => r.findings), ...imported.findings]);
17
18
  const coverage = coverageOf(plan.decisions, results, plan.unchanged, executed.matrix.limited ?? [], executed.notStarted);
19
+ emit({ type: "coverage_settled", coverage });
18
20
  const remembered = applyMemory(found, plan.memory);
19
21
  const reported = new Set(found.map((f) => f.fingerprint));
20
22
  const priorReview = withoutRemembered(prior, plan.memory);
@@ -1,6 +1,7 @@
1
1
  import { emptyUsage } from "../agent/usage.js";
2
2
  import { anchorFinding } from "../anchor/anchor.js";
3
3
  import { sarifCandidates } from "../sarif/candidates.js";
4
+ import { changedLines, overlaps } from "../sarif/evidence.js";
4
5
  import { toFinding } from "./findings.js";
5
6
  import { boundFinding } from "./task.js";
6
7
  // A hostile log could carry thousands of results on the change.
@@ -87,23 +88,8 @@ function quoteFrom(content, lines) {
87
88
  .trim();
88
89
  return quote || undefined;
89
90
  }
90
- // The new-side lines each hunk covers, context included.
91
- function changedLines(diffs) {
92
- const windows = new Map();
93
- for (const diff of diffs) {
94
- const ranges = diff.hunks
95
- .filter((h) => h.newLines > 0)
96
- .map((h) => ({ start: h.newStart, end: h.newStart + h.newLines - 1 }));
97
- if (ranges.length > 0)
98
- windows.set(diff.newPath, ranges);
99
- }
100
- return windows;
101
- }
102
91
  function touches(windows, candidate) {
103
- const ranges = windows.get(candidate.file);
104
- if (!ranges)
105
- return false;
106
- return ranges.some((r) => candidate.lines.start <= r.end && candidate.lines.end >= r.start);
92
+ return (windows.get(candidate.file) ?? []).some((r) => overlaps(candidate.lines, r, 0));
107
93
  }
108
94
  function importWarnings(tool, c) {
109
95
  const left = [];
@@ -2,7 +2,8 @@ import type { ReviewerOverrides, RoleSettings, TierEfforts } from "../agent/sett
2
2
  import type { AnchorContext } from "../anchor/anchor.js";
3
3
  import type { BundlePolicy } from "../bundle/bundle.js";
4
4
  import type { FileGrouper } from "../bundle/grouping.js";
5
- import type { AgentRuntime, ModelChains } from "../contracts.js";
5
+ import type { AgentRuntime, ModelChains, ReferenceIndex, SymbolExtractor } from "../contracts.js";
6
+ import type { Learning } from "../knowledge/learning.js";
6
7
  import type { MemoryEntry } from "../memory/memory.js";
7
8
  import type { ReviewEvent } from "../report/report.js";
8
9
  import type { ReviewerDefinition } from "../review/reviewer.js";
@@ -23,13 +24,17 @@ export interface ReviewOptions {
23
24
  rules?: readonly SourcedRule[];
24
25
  readTrusted?: (path: string) => Promise<string | undefined>;
25
26
  accountMemory?: readonly MemoryEntry[];
27
+ learnings?: readonly Learning[];
26
28
  selection?: Partial<SelectionPolicy>;
27
29
  limits?: ReviewLimits;
28
30
  stages?: ReviewStages;
29
31
  mode?: ReviewMode;
30
32
  identity?: RunIdentity;
31
33
  resume?: ResumedRun;
34
+ symbols?: SymbolExtractor;
35
+ references?: ReferenceIndex;
32
36
  sarif?: readonly SarifLog[];
37
+ sarifEvidence?: readonly SarifLog[];
33
38
  signal?: AbortSignal;
34
39
  onEvent?: (event: ReviewEvent) => void;
35
40
  }
@@ -43,6 +48,7 @@ export interface ReviewLimits {
43
48
  export interface ReviewStages {
44
49
  verify?: boolean;
45
50
  judge?: boolean;
51
+ showPreExisting?: boolean;
46
52
  }
47
53
  export interface ReviewMode {
48
54
  full?: boolean;
@@ -64,3 +70,16 @@ export declare const REVIEW_DEFAULTS: {
64
70
  readonly runTimeoutMs: number;
65
71
  };
66
72
  export declare const MAX_TIMER_MS: number;
73
+ export interface RunSettings {
74
+ concurrency: number;
75
+ taskTimeoutMs: number;
76
+ runTimeoutMs: number;
77
+ maxCostUsd?: number;
78
+ maxTasks?: number;
79
+ ultra: boolean;
80
+ full: boolean;
81
+ verify: boolean;
82
+ judge: boolean;
83
+ showPreExisting: boolean;
84
+ }
85
+ export declare function runSettings(options: Pick<ReviewOptions, "limits" | "mode" | "stages">): RunSettings;
@@ -1,3 +1,5 @@
1
+ import { z } from "zod";
2
+ import { OcraError } from "../errors.js";
1
3
  export const REVIEW_DEFAULTS = {
2
4
  concurrency: 4,
3
5
  taskTimeoutMs: 10 * 60_000,
@@ -6,3 +8,32 @@ export const REVIEW_DEFAULTS = {
6
8
  // Timers fire at once past 2^31 - 1 ms (about 24.8 days); a longer timeout
7
9
  // means no practical limit, so it is cut to the longest one a timer keeps.
8
10
  export const MAX_TIMER_MS = 2 ** 31 - 1;
11
+ // Infinity is allowed (no practical limit), NaN never: z.number() refuses both.
12
+ const atLeast = (min, exclusive, what) => z.custom((v) => typeof v === "number" && (exclusive ? v > min : v >= min), `must be ${what}`);
13
+ const timeoutMs = atLeast(0, true, "a positive number of milliseconds");
14
+ const limitsSchema = z.object({
15
+ concurrency: z.int().positive().optional(),
16
+ taskTimeoutMs: timeoutMs.optional(),
17
+ runTimeoutMs: timeoutMs.optional(),
18
+ maxCostUsd: atLeast(0, false, "a number of US dollars, 0 or more").optional(),
19
+ maxTasks: z.int().nonnegative().optional(),
20
+ });
21
+ export function runSettings(options) {
22
+ const parsed = limitsSchema.safeParse(options.limits ?? {});
23
+ if (!parsed.success) {
24
+ throw new OcraError("CONFIG_INVALID", `ReviewOptions.limits is invalid: ${z.prettifyError(parsed.error)}`);
25
+ }
26
+ const limits = parsed.data;
27
+ return {
28
+ concurrency: limits.concurrency ?? REVIEW_DEFAULTS.concurrency,
29
+ taskTimeoutMs: Math.min(limits.taskTimeoutMs ?? REVIEW_DEFAULTS.taskTimeoutMs, MAX_TIMER_MS),
30
+ runTimeoutMs: Math.min(limits.runTimeoutMs ?? REVIEW_DEFAULTS.runTimeoutMs, MAX_TIMER_MS),
31
+ ...(limits.maxCostUsd === undefined ? {} : { maxCostUsd: limits.maxCostUsd }),
32
+ ...(limits.maxTasks === undefined ? {} : { maxTasks: limits.maxTasks }),
33
+ ultra: options.mode?.ultra === true,
34
+ full: options.mode?.full === true,
35
+ verify: options.stages?.verify !== false,
36
+ judge: options.stages?.judge !== false,
37
+ showPreExisting: options.stages?.showPreExisting !== false,
38
+ };
39
+ }
@@ -19,6 +19,13 @@ export declare const planOutputSchema: z.ZodObject<{
19
19
  lite: "lite";
20
20
  trivial: "trivial";
21
21
  }>;
22
+ scope: z.ZodExactOptional<z.ZodDiscriminatedUnion<[z.ZodObject<{
23
+ mode: z.ZodLiteral<"incremental">;
24
+ since: z.ZodString;
25
+ }, z.core.$strict>, z.ZodObject<{
26
+ mode: z.ZodLiteral<"full">;
27
+ reason: z.ZodString;
28
+ }, z.core.$strict>], "mode">>;
22
29
  selected: z.ZodArray<z.ZodString>;
23
30
  excluded: z.ZodArray<z.ZodObject<{
24
31
  path: z.ZodString;
@@ -1,7 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { EFFORT_LEVELS } from "../agent/settings.js";
3
3
  import { riskTierSchema } from "../domain.js";
4
- import { changeRequestSchema, skippedCellSchema } from "../report/output-schema.js";
4
+ import { changeRequestSchema, scopeSchema, skippedCellSchema } from "../report/output-schema.js";
5
5
  import { exclusionReasonSchema } from "../select/select.js";
6
6
  // The published shape of `ocra review --plan --format json` without what
7
7
  // the CLI adds (where each setting came from), versioned like the report: a
@@ -28,6 +28,8 @@ export const planOutputSchema = z.strictObject({
28
28
  version: z.literal(PLAN_VERSION),
29
29
  changeRequest: changeRequestSchema,
30
30
  tier: riskTierSchema,
31
+ // Added in version 1 without a bump, like planCalls: the report's scope.
32
+ scope: scopeSchema.exactOptional(),
31
33
  selected: z.array(z.string()),
32
34
  excluded: z.array(z.strictObject({ path: z.string(), reason: exclusionReasonSchema })),
33
35
  bundles: z.array(z.strictObject({ label: z.string(), files: z.array(z.string()) })),
@@ -61,6 +63,7 @@ export function toPlanOutput(preview) {
61
63
  ...(c.override ? { override: { by: c.override.by, reason: c.override.reason } } : {}),
62
64
  },
63
65
  tier: preview.tier,
66
+ ...(preview.scope ? { scope: planScope(preview.scope) } : {}),
64
67
  selected: [...preview.selected],
65
68
  excluded: preview.excluded.map((e) => ({ path: e.path, reason: e.reason })),
66
69
  bundles: preview.bundles.map((b) => ({ label: b.label, files: [...b.files] })),
@@ -106,3 +109,8 @@ function planTask(t) {
106
109
  : {}),
107
110
  };
108
111
  }
112
+ function planScope(scope) {
113
+ return scope.mode === "incremental"
114
+ ? { mode: "incremental", since: scope.since }
115
+ : { mode: "full", reason: scope.reason };
116
+ }
@@ -1,9 +1,11 @@
1
1
  import { type Bundle } from "../bundle/bundle.js";
2
2
  import type { AgentRuntime, ReviewContext, Usage } from "../contracts.js";
3
- import type { ChangeRequest, FileDiff, RiskTier } from "../domain.js";
3
+ import type { ChangeRequest, FileDiff, PriorReview, RiskTier } from "../domain.js";
4
+ import { type SelectLearnings } from "../knowledge/select.js";
4
5
  import { type RememberedEntry } from "../memory/memory.js";
5
- import type { ReviewEvent } from "../report/report.js";
6
+ import type { ReviewEvent, ReviewReport } from "../report/report.js";
6
7
  import { type SourcedRule } from "../rules/repo-rules.js";
8
+ import { type AnalyzerEvidence } from "../sarif/evidence.js";
7
9
  import { type FileDecision } from "../select/select.js";
8
10
  import type { ReviewHooks, ReviewOptions } from "./options.js";
9
11
  export interface ReviewPlan {
@@ -13,21 +15,25 @@ export interface ReviewPlan {
13
15
  tier: RiskTier;
14
16
  bundles: Bundle[];
15
17
  unchanged: ReadonlySet<string>;
16
- widened?: {
17
- from: RiskTier;
18
- to: RiskTier;
18
+ prior: {
19
+ review?: PriorReview;
20
+ warning?: string;
19
21
  };
22
+ scope?: ReviewScope;
20
23
  context: ReviewContext;
21
24
  guidelines: string | undefined;
22
25
  repoRules: SourcedRule[];
23
26
  memory: RememberedEntry[];
27
+ learnings: SelectLearnings;
28
+ evidence: AnalyzerEvidence;
24
29
  usage: Usage[];
25
30
  warnings: string[];
26
31
  }
27
- export type PlanOptions = Pick<ReviewOptions & ReviewHooks, "vcs" | "rules" | "readTrusted" | "accountMemory" | "selection" | "bundling" | "grouper" | "effort" | "roles" | "resume"> & {
32
+ export type PlanOptions = Pick<ReviewOptions & ReviewHooks, "vcs" | "rules" | "readTrusted" | "accountMemory" | "learnings" | "sarifEvidence" | "selection" | "bundling" | "grouper" | "effort" | "roles" | "resume"> & {
28
33
  runId?: string;
29
34
  runtime?: AgentRuntime;
30
- reviewOnly?: ReadonlySet<string>;
31
- priorTier?: RiskTier;
35
+ full?: boolean;
32
36
  };
37
+ type ReviewScope = NonNullable<ReviewReport["scope"]>;
33
38
  export declare function planReview(options: PlanOptions, emit: (event: ReviewEvent) => void, signal: AbortSignal): Promise<ReviewPlan>;
39
+ export {};