@open-cr-agent/core 0.11.0 → 0.13.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 (62) hide show
  1. package/dist/agent/settings.d.ts +1 -1
  2. package/dist/agent/settings.js +2 -1
  3. package/dist/{rereview → anchor}/quote.js +1 -1
  4. package/dist/contracts.d.ts +3 -0
  5. package/dist/docs/guidelines.d.ts +19 -0
  6. package/dist/docs/guidelines.js +97 -0
  7. package/dist/fix/check.d.ts +13 -0
  8. package/dist/fix/check.js +62 -0
  9. package/dist/fix/prompt.d.ts +11 -0
  10. package/dist/fix/prompt.js +42 -0
  11. package/dist/fix/propose.d.ts +31 -0
  12. package/dist/fix/propose.js +96 -0
  13. package/dist/fix/select.d.ts +7 -0
  14. package/dist/fix/select.js +22 -0
  15. package/dist/index.d.ts +5 -1
  16. package/dist/index.js +3 -0
  17. package/dist/internal.d.ts +3 -1
  18. package/dist/internal.js +3 -1
  19. package/dist/pipeline/assemble-report.d.ts +2 -0
  20. package/dist/pipeline/assemble-report.js +6 -2
  21. package/dist/pipeline/check-stage.js +1 -2
  22. package/dist/pipeline/context-footprint.d.ts +10 -0
  23. package/dist/pipeline/context-footprint.js +36 -0
  24. package/dist/pipeline/execute-stage.d.ts +1 -1
  25. package/dist/pipeline/execute-stage.js +4 -1
  26. package/dist/pipeline/execute.d.ts +4 -0
  27. package/dist/pipeline/execute.js +6 -1
  28. package/dist/pipeline/findings.js +1 -1
  29. package/dist/pipeline/fix-stage.d.ts +12 -0
  30. package/dist/pipeline/fix-stage.js +34 -0
  31. package/dist/pipeline/options.d.ts +12 -2
  32. package/dist/pipeline/options.js +20 -0
  33. package/dist/pipeline/plan-output.d.ts +21 -0
  34. package/dist/pipeline/plan-output.js +11 -0
  35. package/dist/pipeline/plan.d.ts +2 -0
  36. package/dist/pipeline/plan.js +2 -0
  37. package/dist/pipeline/preview.d.ts +2 -0
  38. package/dist/pipeline/preview.js +12 -4
  39. package/dist/pipeline/run.js +4 -1
  40. package/dist/pipeline/task-prompt.d.ts +5 -1
  41. package/dist/pipeline/task-prompt.js +15 -4
  42. package/dist/plugin/types.d.ts +1 -0
  43. package/dist/report/output-schema.d.ts +17 -0
  44. package/dist/report/output-schema.js +8 -0
  45. package/dist/report/output.js +8 -0
  46. package/dist/report/report.d.ts +3 -1
  47. package/dist/report/report.js +1 -0
  48. package/dist/report/serialize.d.ts +0 -1
  49. package/dist/report/serialize.js +1 -15
  50. package/dist/rereview/presence.js +1 -1
  51. package/dist/review/context-sources.d.ts +5 -0
  52. package/dist/review/context-sources.js +37 -0
  53. package/dist/review/prompt-text.d.ts +1 -1
  54. package/dist/review/prompt-text.js +1 -0
  55. package/dist/review/prompt.d.ts +10 -2
  56. package/dist/review/prompt.js +106 -44
  57. package/dist/task/linked-task.d.ts +2 -0
  58. package/dist/task/linked-task.js +2 -0
  59. package/dist/unsafe-text.d.ts +1 -0
  60. package/dist/unsafe-text.js +15 -0
  61. package/package.json +1 -1
  62. /package/dist/{rereview → anchor}/quote.d.ts +0 -0
@@ -4,7 +4,7 @@ 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
6
  import { type JobResult } from "./execute.js";
7
- import type { ReviewHooks, ReviewOptions, RunSettings } from "./options.js";
7
+ import { type ReviewHooks, type ReviewOptions, type RunSettings } from "./options.js";
8
8
  import type { ReviewPlan } from "./plan.js";
9
9
  export interface StageContext {
10
10
  options: ReviewOptions & ReviewHooks;
@@ -5,6 +5,7 @@ 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
7
  import { prepareJob, reuseJob, runJob } from "./execute.js";
8
+ import { guidelinesShown, } from "./options.js";
8
9
  import { reusePool } from "./resume.js";
9
10
  // One agent task per (bundle, reviewer) cell of the matrix, within the task
10
11
  // limit, the run's signal and the review share of the spend limit.
@@ -14,7 +15,7 @@ export async function executeStage(reviewers, context) {
14
15
  const matrix = planTasks(plan.bundles, reviewers, plan.tier, options.reviewerOverrides, {
15
16
  ultra: settings.ultra,
16
17
  ...(settings.maxTasks !== undefined ? { maxTasks: settings.maxTasks } : {}),
17
- hasGuidelines: Boolean(plan.guidelines?.trim()),
18
+ hasGuidelines: guidelinesShown(plan.guidelines, settings),
18
19
  });
19
20
  const warnings = [];
20
21
  const limited = matrix.skipped.filter((s) => s.reason === "task_limit").length;
@@ -77,6 +78,8 @@ function executeOptions({ options, settings, spendLimit, signal, emit }, relocat
77
78
  relocate: relocator &&
78
79
  (async (request) => spendLimit.mayCall() ? relocator(request) : undefined),
79
80
  ultra: settings.ultra,
81
+ without: settings.without,
82
+ guidelineScope: settings.guidelineScope,
80
83
  symbols: options.symbols,
81
84
  references: options.references,
82
85
  plans: new Map(),
@@ -1,9 +1,11 @@
1
1
  import { type AgentSettings } from "../agent/settings.js";
2
2
  import { type AnchorContext } from "../anchor/anchor.js";
3
3
  import type { AgentRuntime, ReferenceIndex, SymbolExtractor, Usage } from "../contracts.js";
4
+ import type { GuidelineScope } from "../docs/guidelines.js";
4
5
  import type { Finding } from "../domain.js";
5
6
  import type { MatrixCell } from "../matrix/matrix.js";
6
7
  import type { ReviewEvent, TaskOutcome } from "../report/report.js";
8
+ import type { OptionalContext } from "../review/context-sources.js";
7
9
  import { planBundle } from "../review/plan-phase.js";
8
10
  import type { ReviewPlan } from "./plan.js";
9
11
  import type { ReusePool } from "./resume.js";
@@ -17,6 +19,8 @@ export interface JobResult {
17
19
  export interface ExecuteOptions {
18
20
  runtime: AgentRuntime;
19
21
  ultra?: boolean;
22
+ without?: ReadonlySet<OptionalContext>;
23
+ guidelineScope?: GuidelineScope;
20
24
  securityFiles?: ReadonlySet<string>;
21
25
  taskTimeoutMs: number;
22
26
  abortGraceMs?: number | undefined;
@@ -14,7 +14,12 @@ export function prepareJob(job, plan, options) {
14
14
  return { task, key: taskKey(job, plan, task.prompt, call, options) };
15
15
  }
16
16
  function settingsOf(options) {
17
- return { ultra: options.ultra === true, securityFiles: options.securityFiles ?? new Set() };
17
+ return {
18
+ ultra: options.ultra === true,
19
+ securityFiles: options.securityFiles ?? new Set(),
20
+ ...(options.without ? { without: options.without } : {}),
21
+ ...(options.guidelineScope ? { guidelineScope: options.guidelineScope } : {}),
22
+ };
18
23
  }
19
24
  // Runs one (bundle, reviewer) cell and anchors what it reports.
20
25
  export async function runJob(job, plan, options, { task, key }) {
@@ -1,7 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { normalizeSnippet } from "../anchor/match.js";
3
+ import { quoteSignature } from "../anchor/quote.js";
3
4
  import { shortHash } from "../hash.js";
4
- import { quoteSignature } from "../rereview/quote.js";
5
5
  const SEVERITY_RANK = { suggestion: 0, warning: 1, critical: 2 };
6
6
  export function fingerprint(category, file, existingCode) {
7
7
  const key = [category, file, ...normalizeSnippet(existingCode)].join("\n");
@@ -0,0 +1,12 @@
1
+ import type { Usage } from "../contracts.js";
2
+ import type { Finding } from "../domain.js";
3
+ import { type FixSummary } from "../fix/propose.js";
4
+ import type { CheckStage } from "./check-stage.js";
5
+ import type { StageContext } from "./execute-stage.js";
6
+ export interface FixStage {
7
+ findings: Finding[];
8
+ summary?: FixSummary;
9
+ usage: Usage[];
10
+ warnings: string[];
11
+ }
12
+ export declare function fixStage({ judged }: CheckStage, { options, settings, plan, spendLimit, signal, emit }: StageContext): Promise<FixStage>;
@@ -0,0 +1,34 @@
1
+ import { roleCall } from "../agent/settings.js";
2
+ import { proposeFixes } from "../fix/propose.js";
3
+ import { DEFAULT_MAX_FIXES } from "../fix/select.js";
4
+ // After the judge, so fixes are asked only for findings the report keeps.
5
+ export async function fixStage({ judged }, { options, settings, plan, spendLimit, signal, emit }) {
6
+ const findings = judged.findings;
7
+ if (!settings.fixes)
8
+ return { findings, usage: [], warnings: [] };
9
+ if (!options.syntax) {
10
+ return {
11
+ findings,
12
+ usage: [],
13
+ warnings: ["fixes were asked for, but no syntax checker was given: none was proposed"],
14
+ };
15
+ }
16
+ emit({ type: "stage_started", stage: "fix" });
17
+ const fixed = await proposeFixes(findings, {
18
+ runtime: options.runtime,
19
+ syntax: options.syntax,
20
+ diffs: plan.selected,
21
+ context: plan.context,
22
+ signal,
23
+ concurrency: settings.concurrency,
24
+ maxFixes: DEFAULT_MAX_FIXES,
25
+ spendLimit,
26
+ call: roleCall("fixer", options),
27
+ });
28
+ return {
29
+ findings: fixed.findings,
30
+ summary: fixed.summary,
31
+ usage: fixed.usage,
32
+ warnings: fixed.warnings,
33
+ };
34
+ }
@@ -2,12 +2,14 @@ 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, ReferenceIndex, SymbolExtractor } from "../contracts.js";
5
+ import type { AgentRuntime, ModelChains, ReferenceIndex, SymbolExtractor, SyntaxChecker } from "../contracts.js";
6
+ import { type GuidelineScope } from "../docs/guidelines.js";
6
7
  import type { ProjectDoc } from "../docs/project-docs.js";
7
8
  import type { Learning } from "../knowledge/learning.js";
8
9
  import type { MemoryEntry } from "../memory/memory.js";
9
10
  import type { MergeCheck } from "../merge-checks/merge-check.js";
10
11
  import type { ReviewEvent } from "../report/report.js";
12
+ import { type OptionalContext } from "../review/context-sources.js";
11
13
  import type { ReviewerDefinition } from "../review/reviewer.js";
12
14
  import type { SourcedRule } from "../rules/repo-rules.js";
13
15
  import type { SarifLog } from "../sarif/schema.js";
@@ -28,6 +30,7 @@ export interface ReviewOptions {
28
30
  readTrusted?: (path: string) => Promise<string | undefined>;
29
31
  accountMemory?: readonly MemoryEntry[];
30
32
  learnings?: readonly Learning[];
33
+ guidelineScope?: GuidelineScope;
31
34
  linkedTasks?: boolean;
32
35
  taskSources?: readonly TaskSource[];
33
36
  projectDocs?: readonly ProjectDoc[];
@@ -40,6 +43,7 @@ export interface ReviewOptions {
40
43
  resume?: ResumedRun;
41
44
  symbols?: SymbolExtractor;
42
45
  references?: ReferenceIndex;
46
+ syntax?: SyntaxChecker;
43
47
  sarif?: readonly SarifLog[];
44
48
  sarifEvidence?: readonly SarifLog[];
45
49
  signal?: AbortSignal;
@@ -57,10 +61,12 @@ export interface ReviewStages {
57
61
  judge?: boolean;
58
62
  showPreExisting?: boolean;
59
63
  walkthrough?: boolean;
64
+ fixes?: boolean;
60
65
  }
61
66
  export interface ReviewMode {
62
67
  full?: boolean;
63
68
  ultra?: boolean;
69
+ without?: readonly OptionalContext[];
64
70
  }
65
71
  export interface RunIdentity {
66
72
  runId?: string;
@@ -90,5 +96,9 @@ export interface RunSettings {
90
96
  judge: boolean;
91
97
  showPreExisting: boolean;
92
98
  walkthrough: boolean;
99
+ without: ReadonlySet<OptionalContext>;
100
+ fixes: boolean;
101
+ guidelineScope: GuidelineScope;
93
102
  }
94
- export declare function runSettings(options: Pick<ReviewOptions, "limits" | "mode" | "stages">): RunSettings;
103
+ export declare function runSettings(options: Pick<ReviewOptions, "limits" | "mode" | "stages" | "guidelineScope">): RunSettings;
104
+ export declare function guidelinesShown(guidelines: string | undefined, settings: Pick<RunSettings, "without">): boolean;
@@ -1,5 +1,7 @@
1
1
  import { z } from "zod";
2
+ import { GUIDELINE_SCOPES } from "../docs/guidelines.js";
2
3
  import { OcraError } from "../errors.js";
4
+ import { isOptionalContext, OPTIONAL_CONTEXT, } from "../review/context-sources.js";
3
5
  export const REVIEW_DEFAULTS = {
4
6
  concurrency: 4,
5
7
  taskTimeoutMs: 10 * 60_000,
@@ -19,6 +21,10 @@ const limitsSchema = z.object({
19
21
  maxTasks: z.int().nonnegative().optional(),
20
22
  });
21
23
  export function runSettings(options) {
24
+ const guidelineScope = options.guidelineScope ?? "all";
25
+ if (!GUIDELINE_SCOPES.includes(guidelineScope)) {
26
+ throw new OcraError("CONFIG_INVALID", `ReviewOptions.guidelineScope must be one of ${GUIDELINE_SCOPES.join(", ")}`);
27
+ }
22
28
  const parsed = limitsSchema.safeParse(options.limits ?? {});
23
29
  if (!parsed.success) {
24
30
  throw new OcraError("CONFIG_INVALID", `ReviewOptions.limits is invalid: ${z.prettifyError(parsed.error)}`);
@@ -36,5 +42,19 @@ export function runSettings(options) {
36
42
  judge: options.stages?.judge !== false,
37
43
  showPreExisting: options.stages?.showPreExisting !== false,
38
44
  walkthrough: options.stages?.walkthrough === true,
45
+ without: withoutContext(options.mode?.without ?? []),
46
+ fixes: options.stages?.fixes === true,
47
+ guidelineScope,
39
48
  };
40
49
  }
50
+ function withoutContext(names) {
51
+ const unknown = names.filter((n) => !isOptionalContext(n));
52
+ if (unknown.length > 0) {
53
+ throw new OcraError("CONFIG_INVALID", `ReviewOptions.mode.without names unknown context: ${unknown.join(", ")} (known: ${OPTIONAL_CONTEXT.join(", ")})`);
54
+ }
55
+ return new Set(names);
56
+ }
57
+ // A reviewer that needs the guidelines does not run when they are left out.
58
+ export function guidelinesShown(guidelines, settings) {
59
+ return Boolean(guidelines?.trim()) && !settings.without.has("guidelines");
60
+ }
@@ -59,6 +59,27 @@ export declare const planOutputSchema: z.ZodObject<{
59
59
  }>>;
60
60
  models: z.ZodExactOptional<z.ZodArray<z.ZodString>>;
61
61
  planPromptTokens: z.ZodExactOptional<z.ZodInt>;
62
+ context: z.ZodExactOptional<z.ZodArray<z.ZodObject<{
63
+ source: z.ZodEnum<{
64
+ accepted: "accepted";
65
+ analyzer: "analyzer";
66
+ callers: "callers";
67
+ change_request: "change_request";
68
+ changed_files: "changed_files";
69
+ diff: "diff";
70
+ guidelines: "guidelines";
71
+ instructions: "instructions";
72
+ learnings: "learnings";
73
+ linked_tasks: "linked_tasks";
74
+ plan: "plan";
75
+ project_docs: "project_docs";
76
+ rules: "rules";
77
+ system: "system";
78
+ }>;
79
+ tokens: z.ZodInt;
80
+ cut: z.ZodExactOptional<z.ZodInt>;
81
+ duplicateTokens: z.ZodExactOptional<z.ZodInt>;
82
+ }, z.core.$strict>>>;
62
83
  inputCost: z.ZodExactOptional<z.ZodDiscriminatedUnion<[z.ZodObject<{
63
84
  model: z.ZodString;
64
85
  status: z.ZodLiteral<"priced">;
@@ -2,6 +2,7 @@ import { z } from "zod";
2
2
  import { EFFORT_LEVELS } from "../agent/settings.js";
3
3
  import { riskTierSchema } from "../domain.js";
4
4
  import { changeRequestSchema, scopeSchema, skippedCellSchema } from "../report/output-schema.js";
5
+ import { CONTEXT_SOURCES } from "../review/context-sources.js";
5
6
  import { exclusionReasonSchema } from "../select/select.js";
6
7
  // The published shape of `ocra review --plan --format json` without what
7
8
  // the CLI adds (where each setting came from), versioned like the report: a
@@ -22,6 +23,15 @@ const planTaskSchema = z.strictObject({
22
23
  effort: z.enum(EFFORT_LEVELS).exactOptional(),
23
24
  models: z.array(z.string()).exactOptional(),
24
25
  planPromptTokens: z.int().nonnegative().exactOptional(),
26
+ // Added in version 1 without a bump: the first prompt by source (ADR-0057).
27
+ context: z
28
+ .array(z.strictObject({
29
+ source: z.enum(CONTEXT_SOURCES),
30
+ tokens: z.int().nonnegative(),
31
+ cut: z.int().positive().exactOptional(),
32
+ duplicateTokens: z.int().positive().exactOptional(),
33
+ }))
34
+ .exactOptional(),
25
35
  inputCost: inputCostSchema.exactOptional(),
26
36
  });
27
37
  export const planOutputSchema = z.strictObject({
@@ -97,6 +107,7 @@ function planTask(t) {
97
107
  bundle: t.bundle,
98
108
  files: [...t.files],
99
109
  promptTokens: t.promptTokens,
110
+ context: t.context.map((c) => ({ ...c })),
100
111
  ...(t.effort === undefined ? {} : { effort: t.effort }),
101
112
  ...(t.models ? { models: [...t.models] } : {}),
102
113
  ...(t.planPromptTokens === undefined ? {} : { planPromptTokens: t.planPromptTokens }),
@@ -1,5 +1,6 @@
1
1
  import { type Bundle } from "../bundle/bundle.js";
2
2
  import type { AgentRuntime, ReviewContext, Usage } from "../contracts.js";
3
+ import { type GuidelineSection } from "../docs/guidelines.js";
3
4
  import { type DocSection } from "../docs/project-docs.js";
4
5
  import type { ChangeRequest, FileDiff, PriorReview, RiskTier } from "../domain.js";
5
6
  import type { SelectLearnings } from "../knowledge/select.js";
@@ -24,6 +25,7 @@ export interface ReviewPlan {
24
25
  scope?: ReviewScope;
25
26
  context: ReviewContext;
26
27
  guidelines: string | undefined;
28
+ guidelineSections: GuidelineSection[];
27
29
  repoRules: SourcedRule[];
28
30
  memory: RememberedEntry[];
29
31
  learnings: SelectLearnings;
@@ -1,6 +1,7 @@
1
1
  import { roleCall } from "../agent/settings.js";
2
2
  import { bundleFiles, defaultBundlePolicy } from "../bundle/bundle.js";
3
3
  import { runtimeGrouper } from "../bundle/runtime-grouper.js";
4
+ import { guidelineSections } from "../docs/guidelines.js";
4
5
  import { docSections } from "../docs/project-docs.js";
5
6
  import { errorMessage } from "../errors.js";
6
7
  import { rank } from "../matrix/matrix.js";
@@ -94,6 +95,7 @@ export async function planReview(options, emit, signal) {
94
95
  : {}),
95
96
  context,
96
97
  guidelines,
98
+ guidelineSections: guidelines === undefined ? [] : guidelineSections(guidelines),
97
99
  repoRules: [
98
100
  ...(options.rules ?? []),
99
101
  ...fileRules.map((rule) => ({ ...rule, source: "repository" })),
@@ -2,6 +2,7 @@ import type { Effort } from "../contracts.js";
2
2
  import type { ChangeRequest, RiskTier } from "../domain.js";
3
3
  import { type SkippedCell } from "../matrix/matrix.js";
4
4
  import type { FileDecision } from "../select/select.js";
5
+ import { type SourceFootprint } from "./context-footprint.js";
5
6
  import { type ReviewOptions } from "./options.js";
6
7
  import { type PlanOptions, type ReviewPlan } from "./plan.js";
7
8
  export interface PreviewTask {
@@ -10,6 +11,7 @@ export interface PreviewTask {
10
11
  bundle: string;
11
12
  files: string[];
12
13
  promptTokens: number;
14
+ context: SourceFootprint[];
13
15
  planPromptTokens?: number;
14
16
  effort?: Effort;
15
17
  models?: string[];
@@ -1,9 +1,11 @@
1
1
  import { chainOf, reviewerCall } from "../agent/settings.js";
2
2
  import { defaultBundlePolicy } from "../bundle/bundle.js";
3
3
  import { planTasks } from "../matrix/matrix.js";
4
+ import { reviewPromptParts } from "../review/prompt.js";
4
5
  import { correctnessReviewer } from "../review/reviewers/correctness.js";
5
6
  import { securityReviewed } from "../sarif/evidence.js";
6
- import { runSettings } from "./options.js";
7
+ import { contextFootprint, estimateTokens } from "./context-footprint.js";
8
+ import { guidelinesShown, runSettings } from "./options.js";
7
9
  import { planReview } from "./plan.js";
8
10
  import { taskPrompt } from "./task-prompt.js";
9
11
  // Everything a review would do before its first model call, for free: which
@@ -15,19 +17,25 @@ export async function previewReview(options) {
15
17
  const planned = planTasks(plan.bundles, reviewers, plan.tier, options.reviewerOverrides, {
16
18
  ultra: settings.ultra,
17
19
  ...(settings.maxTasks !== undefined ? { maxTasks: settings.maxTasks } : {}),
18
- hasGuidelines: Boolean(plan.guidelines?.trim()),
20
+ hasGuidelines: guidelinesShown(plan.guidelines, settings),
19
21
  });
20
22
  const { cells } = planned;
21
23
  const plannedBundles = new Set();
22
24
  const securityFiles = securityReviewed(cells);
23
25
  const tasks = cells.map((cell) => {
24
- const prepared = taskPrompt(cell, plan, { ultra: settings.ultra, securityFiles });
26
+ const prepared = taskPrompt(cell, plan, {
27
+ ultra: settings.ultra,
28
+ securityFiles,
29
+ without: settings.without,
30
+ guidelineScope: settings.guidelineScope,
31
+ });
25
32
  const task = {
26
33
  taskId: cell.taskId,
27
34
  reviewer: cell.reviewer.id,
28
35
  bundle: cell.bundle.label,
29
36
  files: cell.bundle.files.map((f) => f.newPath),
30
37
  promptTokens: tokens(prepared.prompt),
38
+ context: contextFootprint(reviewPromptParts(prepared.input)),
31
39
  };
32
40
  const call = reviewerCall(cell.reviewer, options);
33
41
  if (call.effort !== undefined)
@@ -89,5 +97,5 @@ function totalInputCost(tasks) {
89
97
  }
90
98
  // Four characters per token: an estimate, not a tokenizer.
91
99
  function tokens(prompt) {
92
- return Math.ceil((prompt.system.length + prompt.user.length) / 4);
100
+ return estimateTokens(prompt.system.length + prompt.user.length);
93
101
  }
@@ -5,6 +5,7 @@ import { assembleReport } from "./assemble-report.js";
5
5
  import { checkStage } from "./check-stage.js";
6
6
  import { executeStage } from "./execute-stage.js";
7
7
  import { filterStage } from "./filter-stage.js";
8
+ import { fixStage } from "./fix-stage.js";
8
9
  import { mergeChecksStage } from "./merge-checks-stage.js";
9
10
  import { runSettings } from "./options.js";
10
11
  import { planReview } from "./plan.js";
@@ -12,7 +13,7 @@ import { newRunId } from "./run-id.js";
12
13
  import { walkthroughStage } from "./walkthrough-stage.js";
13
14
  // The library entry: plan (deterministic stages) → execute (one agent task
14
15
  // per cell, beside the walkthrough and the pre-merge checks) → filter
15
- // (memory, the previous review) → check (verify, judge) → report. The `ocra`
16
+ // (memory, the previous review) → check (verify, judge) → fix → report. The `ocra`
16
17
  // command is one caller. The manual's Embedding page says which options are
17
18
  // a contract.
18
19
  export function review(options) {
@@ -43,10 +44,12 @@ export async function reviewWithHooks(options) {
43
44
  const executed = await executeStage(reviewers, context);
44
45
  const filtered = await filterStage(executed, plan.prior.review, context);
45
46
  const checked = await checkStage(filtered, context);
47
+ const fixed = await fixStage(checked, context);
46
48
  const report = assembleReport({ runId, reviewers }, {
47
49
  executed,
48
50
  filtered,
49
51
  checked,
52
+ fixed,
50
53
  walkthrough: await walkthrough,
51
54
  mergeChecks: await mergeChecks,
52
55
  }, context);
@@ -1,4 +1,6 @@
1
+ import { type GuidelineScope } from "../docs/guidelines.js";
1
2
  import type { MatrixCell } from "../matrix/matrix.js";
3
+ import type { OptionalContext } from "../review/context-sources.js";
2
4
  import { type ReviewPrompt, type ReviewPromptInput } from "../review/prompt.js";
3
5
  import type { ReviewPlan } from "./plan.js";
4
6
  export interface TaskPrompt {
@@ -12,6 +14,8 @@ export interface TaskPrompt {
12
14
  }
13
15
  export interface TaskSettings {
14
16
  ultra: boolean;
17
+ without?: ReadonlySet<OptionalContext>;
18
+ guidelineScope?: GuidelineScope;
15
19
  securityFiles: ReadonlySet<string>;
16
20
  }
17
- export declare function taskPrompt(cell: MatrixCell, plan: ReviewPlan, { ultra, securityFiles }: TaskSettings): TaskPrompt;
21
+ export declare function taskPrompt(cell: MatrixCell, plan: ReviewPlan, { ultra, securityFiles, without, guidelineScope }: TaskSettings): TaskPrompt;
@@ -1,3 +1,4 @@
1
+ import { guidelinesForTask } from "../docs/guidelines.js";
1
2
  import { sectionsFor } from "../docs/project-docs.js";
2
3
  import { memoryFor } from "../memory/memory.js";
3
4
  import { buildReviewPrompt } from "../review/prompt.js";
@@ -9,7 +10,7 @@ const PLAN_MIN_FILES = 5;
9
10
  const PLAN_MIN_PATCH_CHARS = 40_000;
10
11
  // What one task of the matrix sends: the run builds its prompt from this and
11
12
  // --plan previews it, so the preview cannot drift from the run.
12
- export function taskPrompt(cell, plan, { ultra, securityFiles }) {
13
+ export function taskPrompt(cell, plan, { ultra, securityFiles, without, guidelineScope = "all" }) {
13
14
  const files = cell.bundle.files.map((f) => f.newPath);
14
15
  const learnings = plan.learnings(cell.bundle.files);
15
16
  const docs = sectionsFor(plan.docSections, files);
@@ -19,8 +20,9 @@ export function taskPrompt(cell, plan, { ultra, securityFiles }) {
19
20
  changeRequest: plan.changeRequest,
20
21
  changedFiles: plan.selected,
21
22
  bundle: cell.bundle.files,
22
- rules: resolveRules(files, plan.repoRules, cell.reviewer.rules),
23
- guidelines: plan.guidelines,
23
+ rules: resolveRules(files, [], cell.reviewer.rules),
24
+ repoRules: resolveRules(files, plan.repoRules),
25
+ ...guidelinesInput(guidelinesForTask(plan.guidelineSections, guidelineScope, files, cell.reviewer.scope?.requiresGuidelines === true)),
24
26
  ...(plan.linkedTasks && plan.linkedTasks.given.length > 0
25
27
  ? { linkedTasks: plan.linkedTasks.given }
26
28
  : {}),
@@ -29,9 +31,10 @@ export function taskPrompt(cell, plan, { ultra, securityFiles }) {
29
31
  moreLearnings: learnings.left,
30
32
  ...(docs.given.length > 0 ? { projectDocs: docs } : {}),
31
33
  ...(analyzerResults.length > 0 ? { analyzerResults } : {}),
34
+ ...(without && without.size > 0 ? { without } : {}),
32
35
  };
33
36
  const prompt = buildReviewPrompt(input);
34
- const callers = ultra || plan.tier === "full";
37
+ const callers = (ultra || plan.tier === "full") && !without?.has("callers");
35
38
  if (!ultra && !isLargeBundle(cell.bundle))
36
39
  return { input, prompt, callers };
37
40
  return {
@@ -44,6 +47,14 @@ export function taskPrompt(cell, plan, { ultra, securityFiles }) {
44
47
  },
45
48
  };
46
49
  }
50
+ function guidelinesInput(guidelines) {
51
+ if (!guidelines)
52
+ return {};
53
+ return {
54
+ guidelines: guidelines.text,
55
+ ...(guidelines.left.length > 0 ? { moreGuidelines: guidelines.left } : {}),
56
+ };
57
+ }
47
58
  function isLargeBundle({ files }) {
48
59
  const chars = files.reduce((sum, f) => sum + f.patch.length, 0);
49
60
  return files.length >= PLAN_MIN_FILES || chars >= PLAN_MIN_PATCH_CHARS;
@@ -14,6 +14,7 @@ export interface RuntimeOptions {
14
14
  sampling?: Sampling;
15
15
  }
16
16
  export interface CustomProvider {
17
+ api?: "openai" | "anthropic";
17
18
  baseUrl: string;
18
19
  apiKeyEnv?: string;
19
20
  models: Readonly<Record<string, ModelPrice>>;
@@ -243,6 +243,23 @@ export declare const reportOutputSchema: z.ZodObject<{
243
243
  reason: z.ZodString;
244
244
  }, z.core.$strict>>;
245
245
  }, z.core.$strict>>;
246
+ fixes: z.ZodExactOptional<z.ZodObject<{
247
+ asked: z.ZodInt;
248
+ proposed: z.ZodInt;
249
+ rejected: z.ZodArray<z.ZodObject<{
250
+ fingerprint: z.ZodString;
251
+ reason: z.ZodEnum<{
252
+ declined: "declined";
253
+ failed: "failed";
254
+ no_parser: "no_parser";
255
+ stale: "stale";
256
+ syntax: "syntax";
257
+ too_large: "too_large";
258
+ unchanged: "unchanged";
259
+ unsafe: "unsafe";
260
+ }>;
261
+ }, z.core.$strict>>;
262
+ }, z.core.$strict>>;
246
263
  walkthrough: z.ZodExactOptional<z.ZodObject<{
247
264
  overview: z.ZodString;
248
265
  groups: z.ZodArray<z.ZodObject<{
@@ -2,6 +2,7 @@ import { z } from "zod";
2
2
  import { EFFORT_LEVELS } from "../agent/settings.js";
3
3
  import { INCOMPLETE_ENDINGS, MODEL_TIERS } from "../contracts.js";
4
4
  import { anchorMethodSchema, riskTierSchema, severitySchema, verdictSchema, verificationSchema, } from "../domain.js";
5
+ import { FIX_REJECTIONS } from "../fix/check.js";
5
6
  import { skipReasonSchema } from "../matrix/matrix.js";
6
7
  import { memoryEntrySchema } from "../memory/memory.js";
7
8
  import { MERGE_CHECK_OUTCOMES } from "../merge-checks/merge-check.js";
@@ -214,6 +215,13 @@ export const reportOutputSchema = z.strictObject({
214
215
  }))
215
216
  .exactOptional(),
216
217
  judgement: judgeDecisionsSchema.exactOptional(),
218
+ fixes: z
219
+ .strictObject({
220
+ asked: z.int().nonnegative(),
221
+ proposed: z.int().nonnegative(),
222
+ rejected: z.array(z.strictObject({ fingerprint: z.string(), reason: z.enum(FIX_REJECTIONS) })),
223
+ })
224
+ .exactOptional(),
217
225
  walkthrough: z
218
226
  .strictObject({
219
227
  overview: z.string(),
@@ -38,6 +38,14 @@ export function toReportOutput(report) {
38
38
  }
39
39
  if (report.judgement)
40
40
  output.judgement = outputJudgement(report.judgement);
41
+ if (report.fixes) {
42
+ const { asked, proposed, rejected } = report.fixes;
43
+ output.fixes = {
44
+ asked,
45
+ proposed,
46
+ rejected: rejected.map(({ fingerprint, reason }) => ({ fingerprint, reason })),
47
+ };
48
+ }
41
49
  if (report.walkthrough)
42
50
  output.walkthrough = outputWalkthrough(report.walkthrough);
43
51
  if (report.mergeChecks) {
@@ -2,6 +2,7 @@ import { z } from "zod";
2
2
  import type { AttemptRecord, IncompleteEnding, Usage } from "../contracts.js";
3
3
  import type { ProjectDocUse } from "../docs/project-docs.js";
4
4
  import type { AnchorMethod, ChangeRequest, Finding, PriorFinding, RiskTier, TaskFinding, Verdict } from "../domain.js";
5
+ import type { FixSummary } from "../fix/propose.js";
5
6
  import type { JudgeDecisions } from "../judge/judge.js";
6
7
  import type { LearningUse } from "../knowledge/learning.js";
7
8
  import type { SkippedCell } from "../matrix/matrix.js";
@@ -91,6 +92,7 @@ export interface ReviewReport {
91
92
  projectDocs?: ProjectDocUse[];
92
93
  analyzerEvidence?: AnalyzerEvidenceUse[];
93
94
  judgement?: JudgeDecisions;
95
+ fixes?: FixSummary;
94
96
  walkthrough?: Walkthrough;
95
97
  mergeChecks?: MergeCheckResult[];
96
98
  scope?: {
@@ -116,7 +118,7 @@ export interface ReviewReport {
116
118
  usage: Usage;
117
119
  warnings: string[];
118
120
  }
119
- export declare const REVIEW_STAGES: readonly ["select", "bundle", "plan", "review", "filter", "verify", "judge"];
121
+ export declare const REVIEW_STAGES: readonly ["select", "bundle", "plan", "review", "filter", "verify", "judge", "fix"];
120
122
  export type ReviewStage = (typeof REVIEW_STAGES)[number];
121
123
  export type ReviewEvent = {
122
124
  type: "run_started";
@@ -50,6 +50,7 @@ export const REVIEW_STAGES = [
50
50
  "filter",
51
51
  "verify",
52
52
  "judge",
53
+ "fix",
53
54
  ];
54
55
  export function summarizeAnchoring(findings, relocationCalls) {
55
56
  const byMethod = {
@@ -1,2 +1 @@
1
- export declare function isUnsafeCodePoint(code: number): boolean;
2
1
  export declare function serializeOutput(value: unknown, indent?: number): string;
@@ -1,18 +1,4 @@
1
- // Characters a terminal or an editor acts on: C0 controls but tab and
2
- // newline, DEL and C1 controls (ANSI and OSC escapes), line and paragraph
3
- // separators, and bidirectional marks and overrides ("Trojan Source"). One
4
- // definition for every output: terminal text replaces them, JSON escapes them.
5
- export function isUnsafeCodePoint(code) {
6
- return ((code <= 0x1f && code !== 0x09 && code !== 0x0a) ||
7
- (code >= 0x7f && code <= 0x9f) ||
8
- code === 0x061c ||
9
- code === 0x200e ||
10
- code === 0x200f ||
11
- code === 0x2028 ||
12
- code === 0x2029 ||
13
- (code >= 0x202a && code <= 0x202e) ||
14
- (code >= 0x2066 && code <= 0x2069));
15
- }
1
+ import { isUnsafeCodePoint } from "../unsafe-text.js";
16
2
  // JSON for files and stdout. JSON.stringify escapes C0 controls but not the
17
3
  // rest; model and pull request text reaches these files.
18
4
  export function serializeOutput(value, indent = 2) {
@@ -1,5 +1,5 @@
1
1
  import { mapWithConcurrency } from "../agent/pool.js";
2
- import { containsQuote } from "./quote.js";
2
+ import { containsQuote } from "../anchor/quote.js";
3
3
  const READ_CONCURRENCY = 8;
4
4
  // For each earlier finding not reported again: is its code still at head?
5
5
  // A deleted file is a definite no; a failed read or a finding without a
@@ -0,0 +1,5 @@
1
+ export declare const CONTEXT_SOURCES: readonly ["system", "change_request", "changed_files", "linked_tasks", "guidelines", "rules", "accepted", "learnings", "project_docs", "diff", "callers", "analyzer", "plan", "instructions"];
2
+ export type ContextSource = (typeof CONTEXT_SOURCES)[number];
3
+ export declare const OPTIONAL_CONTEXT: readonly ["description", "changed_files", "linked_tasks", "guidelines", "rules", "accepted", "learnings", "project_docs", "callers", "analyzer"];
4
+ export type OptionalContext = (typeof OPTIONAL_CONTEXT)[number];
5
+ export declare function isOptionalContext(value: string): value is OptionalContext;