@open-cr-agent/core 0.9.0 → 0.10.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 (53) hide show
  1. package/dist/agent/settings.d.ts +1 -1
  2. package/dist/agent/settings.js +2 -1
  3. package/dist/chat/answer.d.ts +10 -0
  4. package/dist/chat/answer.js +26 -0
  5. package/dist/chat/prompt.d.ts +22 -0
  6. package/dist/chat/prompt.js +65 -0
  7. package/dist/index.d.ts +2 -1
  8. package/dist/internal.d.ts +1 -0
  9. package/dist/internal.js +1 -0
  10. package/dist/knowledge/paths.d.ts +1 -0
  11. package/dist/knowledge/paths.js +18 -0
  12. package/dist/knowledge/select.d.ts +1 -1
  13. package/dist/knowledge/select.js +46 -105
  14. package/dist/knowledge/terms.d.ts +21 -0
  15. package/dist/knowledge/terms.js +153 -0
  16. package/dist/learn/draft.js +5 -2
  17. package/dist/pipeline/answer.d.ts +16 -0
  18. package/dist/pipeline/answer.js +29 -0
  19. package/dist/pipeline/assemble-report.d.ts +2 -0
  20. package/dist/pipeline/assemble-report.js +5 -2
  21. package/dist/pipeline/execute-stage.js +6 -4
  22. package/dist/pipeline/execute.d.ts +8 -2
  23. package/dist/pipeline/execute.js +7 -6
  24. package/dist/pipeline/learnings.d.ts +7 -0
  25. package/dist/pipeline/learnings.js +20 -0
  26. package/dist/pipeline/options.d.ts +2 -0
  27. package/dist/pipeline/options.js +1 -0
  28. package/dist/pipeline/plan.d.ts +2 -2
  29. package/dist/pipeline/plan.js +5 -3
  30. package/dist/pipeline/preview.js +3 -1
  31. package/dist/pipeline/run.js +6 -4
  32. package/dist/pipeline/task-prompt.d.ts +5 -1
  33. package/dist/pipeline/task-prompt.js +3 -2
  34. package/dist/pipeline/walkthrough-stage.d.ts +9 -0
  35. package/dist/pipeline/walkthrough-stage.js +20 -0
  36. package/dist/report/output-schema.d.ts +9 -0
  37. package/dist/report/output-schema.js +7 -0
  38. package/dist/report/output.js +9 -0
  39. package/dist/report/report.d.ts +2 -0
  40. package/dist/review/impact.d.ts +1 -0
  41. package/dist/review/impact.js +33 -0
  42. package/dist/review/prompt-text.d.ts +1 -1
  43. package/dist/review/prompt-text.js +2 -0
  44. package/dist/sarif/evidence.d.ts +7 -0
  45. package/dist/sarif/evidence.js +14 -0
  46. package/dist/vcs.d.ts +22 -0
  47. package/dist/walkthrough/diagram.d.ts +1 -0
  48. package/dist/walkthrough/diagram.js +49 -0
  49. package/dist/walkthrough/prompt.d.ts +19 -0
  50. package/dist/walkthrough/prompt.js +62 -0
  51. package/dist/walkthrough/walkthrough.d.ts +27 -0
  52. package/dist/walkthrough/walkthrough.js +71 -0
  53. package/package.json +2 -2
@@ -9,6 +9,8 @@ export function assembleReport(run, stages, context) {
9
9
  const { executed, filtered, checked } = stages;
10
10
  if (checked.judged.decisions)
11
11
  report.judgement = checked.judged.decisions;
12
+ if (stages.walkthrough.walkthrough)
13
+ report.walkthrough = stages.walkthrough.walkthrough;
12
14
  const limit = spendLimit.status();
13
15
  if (limit)
14
16
  report.spendLimit = limit;
@@ -35,9 +37,9 @@ export function assembleReport(run, stages, context) {
35
37
  report.warnings.push(plan.prior.warning);
36
38
  return report;
37
39
  }
38
- function reportBody(run, { executed, filtered, checked }, { plan }) {
40
+ function reportBody(run, { executed, filtered, checked, walkthrough }, { plan }) {
39
41
  const { verification, judged } = checked;
40
- const calls = [...plan.usage, ...executed.usage(), ...checked.usage];
42
+ const calls = [...plan.usage, ...executed.usage(), ...walkthrough.usage, ...checked.usage];
41
43
  return {
42
44
  runId: run.runId,
43
45
  changeRequest: plan.changeRequest,
@@ -62,6 +64,7 @@ function reportBody(run, { executed, filtered, checked }, { plan }) {
62
64
  ...plan.warnings,
63
65
  ...executed.warnings,
64
66
  ...filtered.warnings,
67
+ ...walkthrough.warnings,
65
68
  ...checked.warnings,
66
69
  ],
67
70
  };
@@ -3,7 +3,8 @@ import { roleCall } from "../agent/settings.js";
3
3
  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
- import { jobKey, reuseJob, runJob } from "./execute.js";
6
+ import { securityReviewed } from "../sarif/evidence.js";
7
+ import { prepareJob, reuseJob, runJob } from "./execute.js";
7
8
  import { reusePool } from "./resume.js";
8
9
  // One agent task per (bundle, reviewer) cell of the matrix, within the task
9
10
  // limit, the run's signal and the review share of the spend limit.
@@ -24,6 +25,7 @@ export async function executeStage(reviewers, context) {
24
25
  emit({ type: "stage_started", stage: "review" });
25
26
  const relocations = [];
26
27
  const execute = executeOptions(context, relocations);
28
+ execute.securityFiles = securityReviewed(matrix.cells);
27
29
  const resume = options.resume;
28
30
  const pool = reusePool(resume);
29
31
  if (resume)
@@ -36,8 +38,8 @@ export async function executeStage(reviewers, context) {
36
38
  notStarted.add(cell.taskId);
37
39
  return skipCell(cell, "run cancelled before this task started", emit);
38
40
  }
39
- const key = jobKey(cell, plan, execute);
40
- const reused = await reuseJob(cell, plan, execute, key);
41
+ const prepared = prepareJob(cell, plan, execute);
42
+ const reused = await reuseJob(cell, plan, execute, prepared.key);
41
43
  if (reused)
42
44
  return reused;
43
45
  if (!context.spendLimit.mayStartReview()) {
@@ -45,7 +47,7 @@ export async function executeStage(reviewers, context) {
45
47
  unaffordable += 1;
46
48
  return skipCell(cell, `spend limit of $${settings.maxCostUsd} reached`, emit);
47
49
  }
48
- return runJob(cell, plan, execute, key);
50
+ return runJob(cell, plan, execute, prepared);
49
51
  });
50
52
  if (unaffordable > 0) {
51
53
  warnings.push(`spend limit of $${settings.maxCostUsd} reached: ${unaffordable} review task(s) did not start; their files are reported as not reviewed`);
@@ -7,6 +7,7 @@ import type { ReviewEvent, TaskOutcome } from "../report/report.js";
7
7
  import { planBundle } from "../review/plan-phase.js";
8
8
  import type { ReviewPlan } from "./plan.js";
9
9
  import type { ReusePool } from "./resume.js";
10
+ import { type TaskPrompt } from "./task-prompt.js";
10
11
  export interface JobResult {
11
12
  outcome: TaskOutcome;
12
13
  findings: Finding[];
@@ -16,6 +17,7 @@ export interface JobResult {
16
17
  export interface ExecuteOptions {
17
18
  runtime: AgentRuntime;
18
19
  ultra?: boolean;
20
+ securityFiles?: ReadonlySet<string>;
19
21
  taskTimeoutMs: number;
20
22
  abortGraceMs?: number | undefined;
21
23
  relocate?: AnchorContext["relocate"] | undefined;
@@ -33,7 +35,11 @@ export interface ExecuteOptions {
33
35
  keyInputs?: unknown;
34
36
  }
35
37
  type PlannedBundle = Awaited<ReturnType<typeof planBundle>>;
36
- export declare function jobKey(job: MatrixCell, plan: ReviewPlan, options: ExecuteOptions): string;
37
- export declare function runJob(job: MatrixCell, plan: ReviewPlan, options: ExecuteOptions, key: string): Promise<JobResult>;
38
+ export interface PreparedJob {
39
+ task: TaskPrompt;
40
+ key: string;
41
+ }
42
+ export declare function prepareJob(job: MatrixCell, plan: ReviewPlan, options: ExecuteOptions): PreparedJob;
43
+ export declare function runJob(job: MatrixCell, plan: ReviewPlan, options: ExecuteOptions, { task, key }: PreparedJob): Promise<JobResult>;
38
44
  export declare function reuseJob(job: MatrixCell, plan: ReviewPlan, options: ExecuteOptions, key: string): Promise<JobResult | undefined>;
39
45
  export {};
@@ -8,18 +8,19 @@ import { toFinding } from "./findings.js";
8
8
  import { stableHash } from "./provenance.js";
9
9
  import { executeTask } from "./task.js";
10
10
  import { taskPrompt } from "./task-prompt.js";
11
- // The key of a cell's inputs (taskKey), under which its answer is reported
12
- // and an earlier run's answer is reused.
13
- export function jobKey(job, plan, options) {
11
+ export function prepareJob(job, plan, options) {
14
12
  const call = reviewerCall(job.reviewer, options.agents ?? {});
15
- return taskKey(job, plan, taskPrompt(job, plan, options.ultra === true).prompt, call, options);
13
+ const task = taskPrompt(job, plan, settingsOf(options));
14
+ return { task, key: taskKey(job, plan, task.prompt, call, options) };
15
+ }
16
+ function settingsOf(options) {
17
+ return { ultra: options.ultra === true, securityFiles: options.securityFiles ?? new Set() };
16
18
  }
17
19
  // Runs one (bundle, reviewer) cell and anchors what it reports.
18
- export async function runJob(job, plan, options, key) {
20
+ export async function runJob(job, plan, options, { task, key }) {
19
21
  const { emit } = options;
20
22
  const files = job.bundle.files.map((f) => f.newPath);
21
23
  const call = reviewerCall(job.reviewer, options.agents ?? {});
22
- const task = taskPrompt(job, plan, options.ultra === true);
23
24
  const prepared = await preparePrompt(job, plan, options, call, task);
24
25
  emit({
25
26
  type: "task_started",
@@ -0,0 +1,7 @@
1
+ import type { ReviewContext, SymbolExtractor } from "../contracts.js";
2
+ import type { FileDiff } from "../domain.js";
3
+ import type { Learning } from "../knowledge/learning.js";
4
+ import { type SelectLearnings } from "../knowledge/select.js";
5
+ export declare function bundleLearnings(learnings: readonly Learning[], bundles: readonly {
6
+ files: readonly FileDiff[];
7
+ }[], context: Pick<ReviewContext, "readFile" | "searchCode">, extractor: SymbolExtractor | undefined): Promise<SelectLearnings>;
@@ -0,0 +1,20 @@
1
+ import { mapWithConcurrency } from "../agent/pool.js";
2
+ import { learningSelector } from "../knowledge/select.js";
3
+ import { changedCode } from "../review/impact.js";
4
+ // Characters of the code around one bundle's change that ranking reads.
5
+ const MAX_AROUND_CHARS = 50_000;
6
+ const READ_CONCURRENCY = 4;
7
+ // Each bundle's learnings, ranked with the code around its change where the
8
+ // limits leave a candidate out: only there does the ranking decide what a
9
+ // reviewer misses, so only there are the bundle's files read and parsed.
10
+ export async function bundleLearnings(learnings, bundles, context, extractor) {
11
+ const select = learningSelector(learnings);
12
+ if (!extractor)
13
+ return select;
14
+ const crowded = bundles.filter((b) => select(b.files).left.length > 0);
15
+ const around = new Map();
16
+ await mapWithConcurrency(crowded, READ_CONCURRENCY, async ({ files }) => {
17
+ around.set(files, await changedCode(files, context, extractor, MAX_AROUND_CHARS));
18
+ });
19
+ return (files, code) => select(files, code ?? around.get(files));
20
+ }
@@ -49,6 +49,7 @@ export interface ReviewStages {
49
49
  verify?: boolean;
50
50
  judge?: boolean;
51
51
  showPreExisting?: boolean;
52
+ walkthrough?: boolean;
52
53
  }
53
54
  export interface ReviewMode {
54
55
  full?: boolean;
@@ -81,5 +82,6 @@ export interface RunSettings {
81
82
  verify: boolean;
82
83
  judge: boolean;
83
84
  showPreExisting: boolean;
85
+ walkthrough: boolean;
84
86
  }
85
87
  export declare function runSettings(options: Pick<ReviewOptions, "limits" | "mode" | "stages">): RunSettings;
@@ -35,5 +35,6 @@ export function runSettings(options) {
35
35
  verify: options.stages?.verify !== false,
36
36
  judge: options.stages?.judge !== false,
37
37
  showPreExisting: options.stages?.showPreExisting !== false,
38
+ walkthrough: options.stages?.walkthrough === true,
38
39
  };
39
40
  }
@@ -1,7 +1,7 @@
1
1
  import { type Bundle } from "../bundle/bundle.js";
2
2
  import type { AgentRuntime, ReviewContext, Usage } from "../contracts.js";
3
3
  import type { ChangeRequest, FileDiff, PriorReview, RiskTier } from "../domain.js";
4
- import { type SelectLearnings } from "../knowledge/select.js";
4
+ import type { SelectLearnings } from "../knowledge/select.js";
5
5
  import { type RememberedEntry } from "../memory/memory.js";
6
6
  import type { ReviewEvent, ReviewReport } from "../report/report.js";
7
7
  import { type SourcedRule } from "../rules/repo-rules.js";
@@ -29,7 +29,7 @@ export interface ReviewPlan {
29
29
  usage: Usage[];
30
30
  warnings: string[];
31
31
  }
32
- export type PlanOptions = Pick<ReviewOptions & ReviewHooks, "vcs" | "rules" | "readTrusted" | "accountMemory" | "learnings" | "sarifEvidence" | "selection" | "bundling" | "grouper" | "effort" | "roles" | "resume"> & {
32
+ export type PlanOptions = Pick<ReviewOptions & ReviewHooks, "vcs" | "rules" | "readTrusted" | "accountMemory" | "learnings" | "symbols" | "sarifEvidence" | "selection" | "bundling" | "grouper" | "effort" | "roles" | "resume"> & {
33
33
  runId?: string;
34
34
  runtime?: AgentRuntime;
35
35
  full?: boolean;
@@ -2,7 +2,6 @@ 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
4
  import { errorMessage } from "../errors.js";
5
- import { learningSelector } from "../knowledge/select.js";
6
5
  import { rank } from "../matrix/matrix.js";
7
6
  import { MEMORY_PATH, mergeMemory, parseMemory } from "../memory/memory.js";
8
7
  import { parseRepoRules, REPO_RULES_PATH, } from "../rules/repo-rules.js";
@@ -10,6 +9,7 @@ import { analyzerEvidence } from "../sarif/evidence.js";
10
9
  import { binaryTextWarning, defaultSelectionPolicy, selectFiles, } from "../select/select.js";
11
10
  import { triage } from "../triage.js";
12
11
  import { reviewContext } from "./context.js";
12
+ import { bundleLearnings } from "./learnings.js";
13
13
  import { resumedBundles } from "./resume.js";
14
14
  import { newRunId } from "./run-id.js";
15
15
  const GUIDELINES_PATH = "AGENTS.md";
@@ -66,6 +66,8 @@ export async function planReview(options, emit, signal) {
66
66
  });
67
67
  const binaryText = binaryTextWarning(decisions);
68
68
  const evidence = analyzerEvidence(options.sarifEvidence ?? [], bundled.bundles);
69
+ const context = reviewContext(vcs, diffs, options.learnings);
70
+ const learnings = await bundleLearnings(options.learnings ?? [], bundled.bundles, context, options.symbols);
69
71
  return {
70
72
  changeRequest,
71
73
  decisions,
@@ -84,14 +86,14 @@ export async function planReview(options, emit, signal) {
84
86
  : scope.note
85
87
  ? { scope: scope.note }
86
88
  : {}),
87
- context: reviewContext(vcs, diffs, options.learnings),
89
+ context,
88
90
  guidelines,
89
91
  repoRules: [
90
92
  ...(options.rules ?? []),
91
93
  ...fileRules.map((rule) => ({ ...rule, source: "repository" })),
92
94
  ],
93
95
  memory: mergeMemory(memoryText === undefined ? [] : parseMemory(memoryText), options.accountMemory ?? []),
94
- learnings: learningSelector(options.learnings ?? []),
96
+ learnings,
95
97
  evidence,
96
98
  usage,
97
99
  warnings: [...(binaryText ? [binaryText] : []), ...bundled.warnings, ...evidence.warnings],
@@ -2,6 +2,7 @@ import { chainOf, reviewerCall } from "../agent/settings.js";
2
2
  import { defaultBundlePolicy } from "../bundle/bundle.js";
3
3
  import { planTasks } from "../matrix/matrix.js";
4
4
  import { correctnessReviewer } from "../review/reviewers/correctness.js";
5
+ import { securityReviewed } from "../sarif/evidence.js";
5
6
  import { runSettings } from "./options.js";
6
7
  import { planReview } from "./plan.js";
7
8
  import { taskPrompt } from "./task-prompt.js";
@@ -18,8 +19,9 @@ export async function previewReview(options) {
18
19
  });
19
20
  const { cells } = planned;
20
21
  const plannedBundles = new Set();
22
+ const securityFiles = securityReviewed(cells);
21
23
  const tasks = cells.map((cell) => {
22
- const prepared = taskPrompt(cell, plan, settings.ultra);
24
+ const prepared = taskPrompt(cell, plan, { ultra: settings.ultra, securityFiles });
23
25
  const task = {
24
26
  taskId: cell.taskId,
25
27
  reviewer: cell.reviewer.id,
@@ -8,10 +8,11 @@ import { filterStage } from "./filter-stage.js";
8
8
  import { runSettings } from "./options.js";
9
9
  import { planReview } from "./plan.js";
10
10
  import { newRunId } from "./run-id.js";
11
+ import { walkthroughStage } from "./walkthrough-stage.js";
11
12
  // The library entry: plan (deterministic stages) → execute (one agent task
12
- // per cell) → filter (memory, the previous review) → check (verify, judge)
13
- // → report. The `ocra` command is one caller. The manual's Embedding page
14
- // says which options are a contract.
13
+ // per cell, beside the walkthrough) → filter (memory, the previous review)
14
+ // → check (verify, judge) → report. The `ocra` command is one caller. The
15
+ // manual's Embedding page says which options are a contract.
15
16
  export function review(options) {
16
17
  return reviewWithHooks(options);
17
18
  }
@@ -35,10 +36,11 @@ export async function reviewWithHooks(options) {
35
36
  signal,
36
37
  emit,
37
38
  };
39
+ const walkthrough = walkthroughStage(context);
38
40
  const executed = await executeStage(reviewers, context);
39
41
  const filtered = await filterStage(executed, plan.prior.review, context);
40
42
  const checked = await checkStage(filtered, context);
41
- const report = assembleReport({ runId, reviewers }, { executed, filtered, checked }, context);
43
+ const report = assembleReport({ runId, reviewers }, { executed, filtered, checked, walkthrough: await walkthrough }, context);
42
44
  emit({ type: "run_finished", report });
43
45
  return report;
44
46
  }
@@ -10,4 +10,8 @@ export interface TaskPrompt {
10
10
  prompt: () => ReviewPrompt;
11
11
  };
12
12
  }
13
- export declare function taskPrompt(cell: MatrixCell, plan: ReviewPlan, ultra: boolean): TaskPrompt;
13
+ export interface TaskSettings {
14
+ ultra: boolean;
15
+ securityFiles: ReadonlySet<string>;
16
+ }
17
+ export declare function taskPrompt(cell: MatrixCell, plan: ReviewPlan, { ultra, securityFiles }: TaskSettings): TaskPrompt;
@@ -1,16 +1,17 @@
1
1
  import { memoryFor } from "../memory/memory.js";
2
2
  import { buildReviewPrompt } from "../review/prompt.js";
3
3
  import { resolveRules } from "../rules/resolve.js";
4
+ import { evidenceForReviewer } from "../sarif/evidence.js";
4
5
  // In default mode only bundles large enough that a reviewer's 30 steps may
5
6
  // not cover them get a plan phase; --ultra plans every task.
6
7
  const PLAN_MIN_FILES = 5;
7
8
  const PLAN_MIN_PATCH_CHARS = 40_000;
8
9
  // What one task of the matrix sends: the run builds its prompt from this and
9
10
  // --plan previews it, so the preview cannot drift from the run.
10
- export function taskPrompt(cell, plan, ultra) {
11
+ export function taskPrompt(cell, plan, { ultra, securityFiles }) {
11
12
  const files = cell.bundle.files.map((f) => f.newPath);
12
13
  const learnings = plan.learnings(cell.bundle.files);
13
- const analyzerResults = plan.evidence.forBundle(cell.bundle);
14
+ const analyzerResults = evidenceForReviewer(plan.evidence.forBundle(cell.bundle), cell.reviewer.category, securityFiles);
14
15
  const input = {
15
16
  reviewer: cell.reviewer,
16
17
  changeRequest: plan.changeRequest,
@@ -0,0 +1,9 @@
1
+ import type { Usage } from "../contracts.js";
2
+ import { type Walkthrough } from "../walkthrough/walkthrough.js";
3
+ import type { StageContext } from "./execute-stage.js";
4
+ export interface WalkthroughStage {
5
+ walkthrough?: Walkthrough;
6
+ usage: Usage[];
7
+ warnings: string[];
8
+ }
9
+ export declare function walkthroughStage({ options, settings, plan, spendLimit, signal, }: StageContext): Promise<WalkthroughStage>;
@@ -0,0 +1,20 @@
1
+ import { roleCall } from "../agent/settings.js";
2
+ import { writeWalkthrough } from "../walkthrough/walkthrough.js";
3
+ // Runs beside the review tasks: it reads only the plan, and never rejects.
4
+ export async function walkthroughStage({ options, settings, plan, spendLimit, signal, }) {
5
+ if (!settings.walkthrough || !spendLimit.mayCall())
6
+ return { usage: [], warnings: [] };
7
+ const usage = [];
8
+ const result = await writeWalkthrough({
9
+ runtime: options.runtime,
10
+ changeRequest: plan.changeRequest,
11
+ files: plan.selected,
12
+ signal,
13
+ onUsage: (u) => {
14
+ usage.push(u);
15
+ spendLimit.charge(u);
16
+ },
17
+ call: roleCall("writer", options),
18
+ });
19
+ return { ...result, usage };
20
+ }
@@ -221,6 +221,15 @@ export declare const reportOutputSchema: z.ZodObject<{
221
221
  reason: z.ZodString;
222
222
  }, z.core.$strict>>;
223
223
  }, z.core.$strict>>;
224
+ walkthrough: z.ZodExactOptional<z.ZodObject<{
225
+ overview: z.ZodString;
226
+ groups: z.ZodArray<z.ZodObject<{
227
+ title: z.ZodString;
228
+ files: z.ZodArray<z.ZodString>;
229
+ note: z.ZodString;
230
+ }, z.core.$strict>>;
231
+ diagram: z.ZodExactOptional<z.ZodString>;
232
+ }, z.core.$strict>>;
224
233
  rereview: z.ZodExactOptional<z.ZodObject<{
225
234
  fixed: z.ZodArray<z.ZodObject<{
226
235
  fingerprint: z.ZodString;
@@ -198,6 +198,13 @@ export const reportOutputSchema = z.strictObject({
198
198
  }))
199
199
  .exactOptional(),
200
200
  judgement: judgeDecisionsSchema.exactOptional(),
201
+ walkthrough: z
202
+ .strictObject({
203
+ overview: z.string(),
204
+ groups: z.array(z.strictObject({ title: z.string(), files: z.array(z.string()), note: z.string() })),
205
+ diagram: z.string().exactOptional(),
206
+ })
207
+ .exactOptional(),
201
208
  rereview: z
202
209
  .strictObject({
203
210
  fixed: priorList,
@@ -32,6 +32,8 @@ export function toReportOutput(report) {
32
32
  }
33
33
  if (report.judgement)
34
34
  output.judgement = outputJudgement(report.judgement);
35
+ if (report.walkthrough)
36
+ output.walkthrough = outputWalkthrough(report.walkthrough);
35
37
  if (report.anchoring)
36
38
  output.anchoring = outputAnchoring(report.anchoring);
37
39
  if (report.spendLimit)
@@ -50,6 +52,13 @@ export function toReportOutput(report) {
50
52
  }
51
53
  return output;
52
54
  }
55
+ function outputWalkthrough(w) {
56
+ return {
57
+ overview: w.overview,
58
+ groups: w.groups.map((g) => ({ title: g.title, files: [...g.files], note: g.note })),
59
+ ...(w.diagram ? { diagram: w.diagram } : {}),
60
+ };
61
+ }
53
62
  function outputLearning(l) {
54
63
  return {
55
64
  id: l.id,
@@ -8,6 +8,7 @@ import type { RememberedEntry } from "../memory/memory.js";
8
8
  import type { AnalyzerEvidenceUse } from "../sarif/evidence.js";
9
9
  import type { ExclusionReason } from "../select/select.js";
10
10
  import type { RefutedFinding } from "../verify/verify.js";
11
+ import type { Walkthrough } from "../walkthrough/walkthrough.js";
11
12
  import type { RunProvenance } from "./provenance.js";
12
13
  export type CoverageEntry = {
13
14
  path: string;
@@ -85,6 +86,7 @@ export interface ReviewReport {
85
86
  learnings?: LearningUse[];
86
87
  analyzerEvidence?: AnalyzerEvidenceUse[];
87
88
  judgement?: JudgeDecisions;
89
+ walkthrough?: Walkthrough;
88
90
  scope?: {
89
91
  mode: "incremental";
90
92
  since: string;
@@ -16,6 +16,7 @@ interface ChangedSymbol {
16
16
  path: string;
17
17
  }
18
18
  export declare function changedSymbols(files: readonly FileDiff[], context: ImpactContext, extractor?: SymbolExtractor): Promise<ChangedSymbol[]>;
19
+ export declare function changedCode(files: readonly FileDiff[], context: ImpactContext, extractor: SymbolExtractor, maxChars: number): Promise<string>;
19
20
  export interface CallerSources {
20
21
  symbols?: SymbolExtractor | undefined;
21
22
  references?: ReferenceIndex | undefined;
@@ -60,6 +60,39 @@ export async function changedSymbols(files, context, extractor) {
60
60
  })
61
61
  .slice(0, MAX_SYMBOLS);
62
62
  }
63
+ // The text of the definitions a change touches, from the new revision, for
64
+ // learning selection: a symbol the changed function calls on a line the
65
+ // patch does not show. Bounded, since a touched class can be a whole file.
66
+ export async function changedCode(files, context, extractor, maxChars) {
67
+ const parts = [];
68
+ let chars = 0;
69
+ for (const file of files) {
70
+ if (file.kind === "deleted" || file.isBinary || chars >= maxChars)
71
+ continue;
72
+ const content = await context.readFile(file.newPath).catch(() => undefined);
73
+ if (content === undefined)
74
+ continue;
75
+ const symbols = await extractor.symbols(file.newPath, content).catch(() => undefined);
76
+ if (!symbols)
77
+ continue;
78
+ const lines = content.split("\n");
79
+ const touched = new Set();
80
+ for (const line of touchedLines(file)) {
81
+ const definition = innermost(symbols.definitions, line);
82
+ if (definition)
83
+ touched.add(definition);
84
+ }
85
+ for (const d of touched) {
86
+ const text = lines
87
+ .slice(d.startLine - 1, d.endLine)
88
+ .join("\n")
89
+ .slice(0, maxChars - chars);
90
+ parts.push(text);
91
+ chars += text.length;
92
+ }
93
+ }
94
+ return parts.join("\n");
95
+ }
63
96
  // Uses outside the bundle's own files: inside them the reviewer already sees
64
97
  // the code. The reference index answers first where it knows the symbol;
65
98
  // a use it lists whose line no longer names the symbol is from a file
@@ -2,7 +2,7 @@ declare const brand: unique symbol;
2
2
  export type PromptText = string & {
3
3
  readonly [brand]: "PromptText";
4
4
  };
5
- declare const SECTIONS: readonly ["change_request", "title", "description", "changed_files", "repository_guidelines", "review_rules", "accepted_findings", "team_learnings", "learning", "learning_index", "review_files", "file", "findings", "finding", "diff", "file_excerpt", "related_code", "callers", "analyzer_results", "review_plan", "reply"];
5
+ declare const SECTIONS: readonly ["change_request", "title", "description", "changed_files", "repository_guidelines", "review_rules", "accepted_findings", "team_learnings", "learning", "learning_index", "review_files", "file", "findings", "finding", "diff", "file_excerpt", "related_code", "callers", "analyzer_results", "review_plan", "reply", "thread", "question"];
6
6
  export type SectionName = (typeof SECTIONS)[number];
7
7
  export declare function data(text: string): PromptText;
8
8
  export declare function ocraText(text: string): PromptText;
@@ -35,6 +35,8 @@ const SECTIONS = [
35
35
  "analyzer_results",
36
36
  "review_plan",
37
37
  "reply",
38
+ "thread",
39
+ "question",
38
40
  ];
39
41
  // Characters a tokenizer may drop or a model may read past: whitespace,
40
42
  // every default-ignorable code point (joiners, direction marks, variation
@@ -29,6 +29,13 @@ export interface AnalyzerEvidence {
29
29
  warnings: string[];
30
30
  }
31
31
  export declare function analyzerEvidence(logs: readonly SarifLog[], bundles: readonly FileGroup[]): AnalyzerEvidence;
32
+ export declare function securityReviewed(cells: readonly {
33
+ reviewer: {
34
+ category: string;
35
+ };
36
+ bundle: FileGroup;
37
+ }[]): ReadonlySet<string>;
38
+ export declare function evidenceForReviewer(results: readonly AnalyzerResult[], category: string, securityFiles: ReadonlySet<string>): AnalyzerResult[];
32
39
  export declare function evidenceUses(evidence: AnalyzerEvidence, bundles: readonly FileGroup[]): AnalyzerEvidenceUse[];
33
40
  export declare function changedLines(diffs: readonly FileDiff[]): Map<string, LineRange[]>;
34
41
  export declare function overlaps(lines: LineRange, range: LineRange, margin: number): boolean;
@@ -80,6 +80,20 @@ function byRelevance(a, b) {
80
80
  a.lines.start - b.lines.start ||
81
81
  (a.ruleId < b.ruleId ? -1 : a.ruleId > b.ruleId ? 1 : 0));
82
82
  }
83
+ const SECURITY = "security";
84
+ // The files a security reviewer reviews in this run's matrix.
85
+ export function securityReviewed(cells) {
86
+ return new Set(cells
87
+ .filter((c) => c.reviewer.category === SECURITY)
88
+ .flatMap((c) => c.bundle.files.map((f) => f.newPath)));
89
+ }
90
+ // A security-tagged result goes to the security reviewer of its file, and to
91
+ // the others only when no security reviewer reviews that file (ADR-0043).
92
+ export function evidenceForReviewer(results, category, securityFiles) {
93
+ if (category === SECURITY)
94
+ return [...results];
95
+ return results.filter((r) => !r.security || !securityFiles.has(r.file));
96
+ }
83
97
  // The new-side lines each hunk covers, context included.
84
98
  export function evidenceUses(evidence, bundles) {
85
99
  const uses = new Map();
package/dist/vcs.d.ts CHANGED
@@ -1,6 +1,27 @@
1
1
  import type { CodeMatch } from "./contracts.js";
2
2
  import type { ChangeRequest, FileDiff, PriorReview } from "./domain.js";
3
3
  import type { ReviewReport } from "./report/report.js";
4
+ export interface MentionRef {
5
+ id: string;
6
+ inline?: boolean;
7
+ }
8
+ export type Mention = {
9
+ asked: true;
10
+ by: string;
11
+ question: string;
12
+ thread: readonly {
13
+ author: string;
14
+ body: string;
15
+ }[];
16
+ on?: {
17
+ path: string;
18
+ line?: number;
19
+ };
20
+ answer(text: string): Promise<void>;
21
+ } | {
22
+ asked: false;
23
+ reason: string;
24
+ };
4
25
  export interface VcsAdapter {
5
26
  readonly name: string;
6
27
  getChangeRequest(): Promise<ChangeRequest>;
@@ -11,4 +32,5 @@ export interface VcsAdapter {
11
32
  publish(report: ReviewReport): Promise<{
12
33
  warnings: string[];
13
34
  }>;
35
+ mention?(ref: MentionRef): Promise<Mention>;
14
36
  }
@@ -0,0 +1 @@
1
+ export declare function sequenceDiagram(text: string): string | undefined;
@@ -0,0 +1,49 @@
1
+ // A sequence diagram is model output that ends up rendered by the platform,
2
+ // so only the statements a sequence diagram needs pass: no directives,
3
+ // comments, links or click handlers, and no backtick or angle bracket that
4
+ // could close the fence or form markup. One line that fails drops the whole
5
+ // diagram, since half a flow misleads more than none.
6
+ const MAX_LINES = 40;
7
+ const MAX_LINE_CHARS = 160;
8
+ const ID = "[A-Za-z_][A-Za-z0-9_]*";
9
+ const ARROW = String.raw `(?:-->>|->>|-->|->|--x|-x|--\)|-\))[+-]?`;
10
+ const ARROW_ONCE = new RegExp(ARROW);
11
+ const STATEMENTS = [
12
+ /^autonumber$/,
13
+ new RegExp(`^(?:participant|actor) ${ID}(?: as [^:;]+)?$`),
14
+ new RegExp(`^${ID} ?${ARROW} ?${ID}: .+$`),
15
+ new RegExp(`^Note (?:left of|right of|over) ${ID}(?:, ?${ID})?: .+$`),
16
+ /^(?:loop|alt|else|opt|par|and|critical|option|break)(?: .+)?$/,
17
+ /^end$/,
18
+ new RegExp(`^(?:activate|deactivate) ${ID}$`),
19
+ ];
20
+ export function sequenceDiagram(text) {
21
+ const lines = text
22
+ .trim()
23
+ .split(/\r?\n/)
24
+ .map((line) => line.trim())
25
+ .filter((line) => line !== "");
26
+ if (lines[0] !== "sequenceDiagram" || lines.length < 3 || lines.length > MAX_LINES + 1) {
27
+ return undefined;
28
+ }
29
+ const body = lines.slice(1);
30
+ const safe = body.every((line) => line.length <= MAX_LINE_CHARS &&
31
+ !/[`<>%{}]/.test(line.replace(ARROW_ONCE, "")) &&
32
+ STATEMENTS.some((statement) => statement.test(line)));
33
+ if (!safe || !balanced(body))
34
+ return undefined;
35
+ return ["sequenceDiagram", ...body.map((line) => ` ${line}`)].join("\n");
36
+ }
37
+ const OPENS = /^(?:loop|alt|opt|par|critical|break)(?: |$)/;
38
+ function balanced(lines) {
39
+ let depth = 0;
40
+ for (const line of lines) {
41
+ if (OPENS.test(line))
42
+ depth += 1;
43
+ else if (line === "end")
44
+ depth -= 1;
45
+ if (depth < 0)
46
+ return false;
47
+ }
48
+ return depth === 0;
49
+ }
@@ -0,0 +1,19 @@
1
+ import { z } from "zod";
2
+ import type { ChangeRequest, FileDiff } from "../domain.js";
3
+ import { type PromptText } from "../review/prompt-text.js";
4
+ export declare const walkthroughResponseSchema: z.ZodObject<{
5
+ overview: z.ZodDefault<z.ZodString>;
6
+ groups: z.ZodDefault<z.ZodArray<z.ZodObject<{
7
+ title: z.ZodDefault<z.ZodString>;
8
+ files: z.ZodDefault<z.ZodArray<z.ZodString>>;
9
+ note: z.ZodDefault<z.ZodString>;
10
+ }, z.core.$strip>>>;
11
+ diagram: z.ZodDefault<z.ZodString>;
12
+ }, z.core.$strip>;
13
+ export type WalkthroughResponse = z.infer<typeof walkthroughResponseSchema>;
14
+ export declare function buildWalkthroughPrompt(changeRequest: ChangeRequest, files: readonly FileDiff[]): {
15
+ system: string;
16
+ user: string;
17
+ };
18
+ export declare function changedFile(f: FileDiff): PromptText;
19
+ export declare function smallestPatchesFirst(files: readonly FileDiff[], maxChars: number): PromptText[];