@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
@@ -20,7 +20,13 @@ export function buildReviewPrompt(input) {
20
20
  sections.push(section("review_rules", data(input.rules)));
21
21
  if (input.accepted && input.accepted.length > 0)
22
22
  sections.push(renderAccepted(input.accepted));
23
- sections.push(section("review_files", input.bundle.map(renderFile)), ...(input.callers && input.callers.length > 0 ? [renderCallers(input.callers)] : []), ...(input.plan
23
+ const given = input.learnings ?? [];
24
+ const more = input.moreLearnings ?? [];
25
+ if (given.length > 0 || more.length > 0)
26
+ sections.push(renderLearnings(given, more));
27
+ sections.push(section("review_files", input.bundle.map(renderFile)), ...(input.callers && input.callers.length > 0 ? [renderCallers(input.callers)] : []), ...(input.analyzerResults && input.analyzerResults.length > 0
28
+ ? [renderAnalyzerResults(input.analyzerResults)]
29
+ : []), ...(input.plan
24
30
  ? [
25
31
  section("review_plan", [
26
32
  ocraText("A planning pass suggests checking these first; it may be wrong, so verify before you report."),
@@ -45,7 +51,17 @@ export function renderChangeRequest(cr, maxDescription = MAX_DESCRIPTION_CHARS)
45
51
  section("description", truncated(cr.description, maxDescription)),
46
52
  ]);
47
53
  }
54
+ // Every task of a run shares the list: rendered once per run.
55
+ const changedFilesText = new WeakMap();
48
56
  function renderChangedFiles(files) {
57
+ let text = changedFilesText.get(files);
58
+ if (text === undefined) {
59
+ text = renderChangedFilesOnce(files);
60
+ changedFilesText.set(files, text);
61
+ }
62
+ return text;
63
+ }
64
+ function renderChangedFilesOnce(files) {
49
65
  const lines = files.map((f) => {
50
66
  const path = f.kind === "renamed" ? `${f.oldPath} -> ${f.newPath}` : f.newPath;
51
67
  return join([ocraText(`${f.kind} `), data(oneLine(path)), ocraText(` (+${f.additions} -${f.deletions})`)], "");
@@ -59,16 +75,55 @@ function renderAccepted(entries) {
59
75
  ...lines,
60
76
  ]);
61
77
  }
78
+ export const MAX_LISTED_LEARNINGS = 10;
79
+ function renderLearnings(given, more) {
80
+ return section("team_learnings", [
81
+ ocraText("What the team learned from earlier changes to this code. Check whether this change repeats a mistake one describes; report only what the change itself gets wrong, never a learning alone."),
82
+ ...given.map((l) => section("learning", [data(oneLine(l.title)), data(l.body)], {
83
+ id: l.id,
84
+ paths: l.paths.join(", "),
85
+ ...(l.critical ? { critical: "true" } : {}),
86
+ })),
87
+ ...(more.length > 0 ? [renderLearningIndex(more)] : []),
88
+ ]);
89
+ }
90
+ // Titles are written as the rule itself, so a reviewer can apply a learning
91
+ // the budget left out, or read it when the title is not enough.
92
+ function renderLearningIndex(more) {
93
+ const listed = more.slice(0, MAX_LISTED_LEARNINGS);
94
+ const unlisted = more.length - listed.length;
95
+ return section("learning_index", [
96
+ ocraText(`More learnings that match this change, by id and title; read one that may apply with ${REVIEW_TOOLS.readLearning}:`),
97
+ ...listed.map((l) => data(`- ${l.id}: ${oneLine(l.title)}`)),
98
+ ...(unlisted > 0 ? [ocraText(`and ${unlisted} more.`)] : []),
99
+ ]);
100
+ }
62
101
  function renderCallers(callers) {
63
102
  const lines = callers.flatMap(({ symbol, uses }) => [
64
103
  data(`${oneLine(symbol)}:`),
65
- ...uses.map((u) => data(` ${oneLine(u.path)}:${u.line}: ${oneLine(u.text.trim()).slice(0, 200)}`)),
104
+ ...uses.map((u) => data(` ${oneLine(u.path)}:${u.line}${u.within ? ` (in ${oneLine(u.within)})` : ""}: ${oneLine(u.text.trim()).slice(0, 200)}`)),
66
105
  ]);
67
106
  return section("callers", [
68
107
  ocraText("Uses of symbols this bundle defines or changes, outside the bundle. Check that the change does not break them."),
69
108
  ...lines,
70
109
  ]);
71
110
  }
111
+ // The reviewer cites a result it confirms by tool and rule, so the judge
112
+ // can merge it with another reviewer's report of the same result.
113
+ function renderAnalyzerResults(results) {
114
+ return section("analyzer_results", [
115
+ ocraText(`Results of static analyzers the team runs, on or near the changed lines. Each is a lead, not a finding: confirm it in the code, and report it with ${REVIEW_TOOLS.reportFinding} only when it is in your focus and the change introduces or worsens it, naming the tool and rule in the evidence. Leave out results the code shows to be wrong.`),
116
+ ...results.map((r) => {
117
+ const lines = r.lines.end > r.lines.start ? `${r.lines.start}-${r.lines.end}` : `${r.lines.start}`;
118
+ const tags = [
119
+ r.severity,
120
+ ...(r.security ? ["security"] : []),
121
+ r.onChange ? "on the change" : "near the change",
122
+ ];
123
+ return data(oneLine(`- ${r.file}:${lines} ${r.tool.name} ${r.ruleId} (${tags.join(", ")}): ${r.message}`));
124
+ }),
125
+ ]);
126
+ }
72
127
  function renderFile(diff) {
73
128
  const attributes = { path: diff.newPath, change: diff.kind };
74
129
  if (diff.kind === "renamed")
@@ -2,6 +2,7 @@ export declare const REVIEW_TOOLS: {
2
2
  readonly readFile: "read_file";
3
3
  readonly readDiff: "read_diff";
4
4
  readonly codeSearch: "code_search";
5
+ readonly readLearning: "read_learning";
5
6
  readonly reportFinding: "report_finding";
6
7
  readonly taskDone: "task_done";
7
8
  };
@@ -2,6 +2,7 @@ export const REVIEW_TOOLS = {
2
2
  readFile: "read_file",
3
3
  readDiff: "read_diff",
4
4
  codeSearch: "code_search",
5
+ readLearning: "read_learning",
5
6
  reportFinding: "report_finding",
6
7
  taskDone: "task_done",
7
8
  };
@@ -2,6 +2,9 @@ import type { AttemptRecord, IncompleteEnding, Usage } from "../contracts.js";
2
2
  import type { QuotaError } from "./quota.js";
3
3
  export declare const MAX_AGENT_STEPS = 30;
4
4
  export declare const RESUME_MESSAGE: string;
5
+ export declare const WRAP_UP_TOOLS: readonly ["report_finding", "task_done"];
6
+ export declare const WRAP_UP_MESSAGE: string;
7
+ export declare const WRAP_UP_STEPS = 2;
5
8
  export declare function withoutSecrets(text: string, secrets: readonly string[]): string;
6
9
  export interface AttemptOutcome {
7
10
  findings: unknown[];
@@ -12,8 +15,17 @@ export interface AttemptOutcome {
12
15
  atStepCap?: true;
13
16
  read?: string[];
14
17
  searched?: string[];
18
+ wrappedUp?: WrapUpOutcome;
15
19
  usage: Usage;
16
20
  error?: AttemptError;
21
+ unreadMessages?: number;
22
+ }
23
+ export interface WrapUpOutcome {
24
+ findings: number;
25
+ error?: string;
26
+ }
27
+ export interface TaskAttempt extends AttemptOutcome {
28
+ wrapUp?(): Promise<AttemptOutcome>;
17
29
  }
18
30
  export interface AttemptError {
19
31
  message: string;
@@ -12,6 +12,17 @@ export const MAX_AGENT_STEPS = 30;
12
12
  // the same conversation, which keeps what it read and is cheaper than
13
13
  // starting over.
14
14
  export const RESUME_MESSAGE = `You stopped before finishing the review. Continue with the files in <ocra_review_files> you have not reviewed yet, report each confirmed issue with ${REVIEW_TOOLS.reportFinding}, and call ${REVIEW_TOOLS.taskDone} when every file is done.`;
15
+ // A review that ends without the done tool, at the step cap or after
16
+ // stopping early, has often read the code and reached a conclusion it never
17
+ // reported (on its last step OpenCode tells it to answer in text only). One
18
+ // more turn in the same conversation, with only these tools, keeps what it
19
+ // confirmed.
20
+ export const WRAP_UP_TOOLS = [REVIEW_TOOLS.reportFinding, REVIEW_TOOLS.taskDone];
21
+ export const WRAP_UP_MESSAGE = `You have no steps left to read more code. Report each issue you have already confirmed with ${REVIEW_TOOLS.reportFinding}, then call ${REVIEW_TOOLS.taskDone}. Do not report anything you have not confirmed.`;
22
+ // The turn is one request in which the agent reports. It gets two: OpenCode
23
+ // tells an agent to answer in text only on its last step, and Gemini rejects
24
+ // a request that ends with a model turn (#66).
25
+ export const WRAP_UP_STEPS = 2;
15
26
  // Text with every secret replaced: a provider's error may echo the request's
16
27
  // headers, and a progress line or session file must not carry the key.
17
28
  export function withoutSecrets(text, secrets) {
@@ -22,7 +33,16 @@ export function withoutSecrets(text, secrets) {
22
33
  export function attemptSummary(model, outcome) {
23
34
  const { inputTokens, outputTokens, reasoningTokens, costUsd } = outcome.usage;
24
35
  const resumed = outcome.resumed ? ", resumed after stopping early" : "";
25
- return `${model}: ${outcome.steps} step(s), ${toolSummary(outcome.toolCalls)}${resumed}, ${inputTokens} in / ${outputTokens} out / ${reasoningTokens} reasoning tokens, $${costUsd.toFixed(4)}`;
36
+ const unread = outcome.unreadMessages
37
+ ? `, ${outcome.unreadMessages} session message(s) not read (their findings and usage are missing)`
38
+ : "";
39
+ return `${model}: ${outcome.steps} step(s), ${toolSummary(outcome.toolCalls)}${resumed}${wrapUpSummary(outcome.wrappedUp)}, ${inputTokens} in / ${outputTokens} out / ${reasoningTokens} reasoning tokens, $${costUsd.toFixed(4)}${unread}`;
40
+ }
41
+ function wrapUpSummary(wrapUp) {
42
+ if (!wrapUp)
43
+ return "";
44
+ const failed = wrapUp.error === undefined ? "" : `, then failed: ${wrapUp.error}`;
45
+ return `, wrap-up turn reported ${wrapUp.findings} finding(s)${failed}`;
26
46
  }
27
47
  export function toolSummary(toolCalls) {
28
48
  if (toolCalls.length === 0)
@@ -1,10 +1,10 @@
1
1
  import type { AgentEvent, AgentTaskSpec, CompletionRequest, CompletionResult, ModelChains, Usage } from "../contracts.js";
2
2
  import { OcraError } from "../errors.js";
3
- import type { AttemptOutcome } from "./attempt.js";
3
+ import type { AttemptOutcome, TaskAttempt } from "./attempt.js";
4
4
  export interface ModelAttempts {
5
5
  refuse?(chain: readonly string[], own: boolean): OcraError | undefined;
6
6
  ready?(): Promise<void>;
7
- task(model: string, spec: AgentTaskSpec, signal: AbortSignal, onUsage: (spent: Usage) => void): Promise<AttemptOutcome>;
7
+ task(model: string, spec: AgentTaskSpec, signal: AbortSignal, onUsage: (spent: Usage) => void): Promise<TaskAttempt>;
8
8
  complete(model: string, request: CompletionRequest, signal: AbortSignal): Promise<AttemptOutcome>;
9
9
  }
10
10
  export declare class ChainRunner {
@@ -1,5 +1,5 @@
1
1
  import type { AgentEvent, CompletionResult, ModelTier, Usage } from "../contracts.js";
2
- import { type AttemptOutcome } from "./attempt.js";
2
+ import { type AttemptOutcome, type TaskAttempt } from "./attempt.js";
3
3
  import type { ModelHealth } from "./models.js";
4
4
  export interface FailbackOptions {
5
5
  taskId: string;
@@ -8,7 +8,7 @@ export interface FailbackOptions {
8
8
  chain: readonly string[];
9
9
  health: ModelHealth;
10
10
  signal: AbortSignal;
11
- attempt(model: string, onUsage: (spent: Usage) => void): Promise<AttemptOutcome>;
11
+ attempt(model: string, onUsage: (spent: Usage) => void): Promise<TaskAttempt>;
12
12
  }
13
13
  export declare function withFailback(options: FailbackOptions): AsyncGenerator<AgentEvent>;
14
14
  export interface CompleteOptions {
@@ -2,6 +2,7 @@ import { addUsage, emptyUsage } from "../agent/usage.js";
2
2
  import { CompletionError } from "../errors.js";
3
3
  import { attemptEnding, attemptRecord, attemptSummary, } from "./attempt.js";
4
4
  import { sleep } from "./quota.js";
5
+ import { outcomeOf, pendingWrapUp, wrapUp } from "./wrap-up.js";
5
6
  // Findings from a failed attempt are still emitted: the pipeline deduplicates
6
7
  // by fingerprint, so a retry on the next model cannot double-report them.
7
8
  export async function* withFailback(options) {
@@ -29,14 +30,19 @@ export async function* withFailback(options) {
29
30
  // Spend is reported while the attempt runs, so a run's spend limit
30
31
  // can stop it; the finished attempt's total settles the rest.
31
32
  const live = new LiveUsage();
32
- const running = options.attempt(model, (spent) => live.observe(spent));
33
- const finished = running.then(() => false, () => false);
34
- while (await Promise.race([finished, live.changed().then(() => true)])) {
35
- yield { type: "usage", taskId, ...live.take() };
36
- }
37
- const outcome = await running;
33
+ const attempt = yield* whileRunning(taskId, live, options.attempt(model, (spent) => live.observe(spent)));
34
+ yield { type: "usage", taskId, ...live.rest(attempt.usage) };
35
+ let outcome = outcomeOf(attempt);
36
+ // Read before the wrap-up turn, whose done tool reports what the agent
37
+ // had confirmed and reads nothing more: its files stay partly reviewed.
38
38
  const ended = attemptEnding(outcome);
39
- yield { type: "usage", taskId, ...live.rest(outcome.usage) };
39
+ // Decided after the attempt's spend was handed over, so a spend limit
40
+ // it reached has already aborted the signal.
41
+ const turn = pendingWrapUp(attempt, ended, signal);
42
+ if (turn) {
43
+ outcome = yield* whileRunning(taskId, live, wrapUp(outcome, turn));
44
+ yield { type: "usage", taskId, ...live.rest(outcome.usage) };
45
+ }
40
46
  yield {
41
47
  type: "progress",
42
48
  taskId,
@@ -50,7 +56,7 @@ export async function* withFailback(options) {
50
56
  // the run's limit: the pipeline decides what that stop means.
51
57
  if (!outcome.error) {
52
58
  health.recordSuccess(model);
53
- yield doneEvent(taskId, ended);
59
+ yield doneEvent(taskId, ended, outcome.wrappedUp);
54
60
  return;
55
61
  }
56
62
  // A cancelled attempt is neither finished nor the model's fault.
@@ -84,10 +90,21 @@ export async function* withFailback(options) {
84
90
  retryable: true,
85
91
  };
86
92
  }
87
- function doneEvent(taskId, ended) {
88
- return ended === "step_cap" || ended === "stopped_early"
89
- ? { type: "done", taskId, ended }
90
- : { type: "done", taskId };
93
+ function doneEvent(taskId, ended, wrappedUp) {
94
+ return {
95
+ type: "done",
96
+ taskId,
97
+ ...(ended === "step_cap" || ended === "stopped_early" ? { ended } : {}),
98
+ ...(wrappedUp ? { wrapUp: { findings: wrappedUp.findings } } : {}),
99
+ };
100
+ }
101
+ // Yields the spend that grows while `running` runs, then returns its result.
102
+ async function* whileRunning(taskId, live, running) {
103
+ const finished = running.then(() => false, () => false);
104
+ while (await Promise.race([finished, live.changed().then(() => true)])) {
105
+ yield { type: "usage", taskId, ...live.take() };
106
+ }
107
+ return await running;
91
108
  }
92
109
  // Hands out what an attempt has spent in increments, each what grew since the
93
110
  // last one; `rest` settles the finished attempt's total, so the increments
@@ -91,6 +91,16 @@ const codeSearch = {
91
91
  return promptData(shown.join("\n"));
92
92
  },
93
93
  };
94
+ const readLearning = {
95
+ name: REVIEW_TOOLS.readLearning,
96
+ description: "Read a team learning listed in <ocra_learning_index> by its id: its title and what to check.",
97
+ inputSchema: z.object({ id: z.string().min(1) }),
98
+ async execute(args, context) {
99
+ const { id } = args;
100
+ const learning = context.readLearning?.(id);
101
+ return promptData(learning ?? `No learning with id ${id}.`);
102
+ },
103
+ };
94
104
  const reportFinding = {
95
105
  name: REVIEW_TOOLS.reportFinding,
96
106
  description: "Report one confirmed defect. Call once per issue.",
@@ -107,6 +117,7 @@ export const reviewTools = [
107
117
  readFile,
108
118
  readDiff,
109
119
  codeSearch,
120
+ readLearning,
110
121
  reportFinding,
111
122
  taskDone,
112
123
  ];
@@ -0,0 +1,6 @@
1
+ import type { AttemptEnding, AttemptOutcome, TaskAttempt } from "./attempt.js";
2
+ type WrapUp = NonNullable<TaskAttempt["wrapUp"]>;
3
+ export declare function pendingWrapUp(attempt: TaskAttempt, ended: AttemptEnding, signal: AbortSignal): WrapUp | undefined;
4
+ export declare function wrapUp(before: AttemptOutcome, turn: WrapUp): Promise<AttemptOutcome>;
5
+ export declare function outcomeOf(attempt: TaskAttempt): AttemptOutcome;
6
+ export {};
@@ -0,0 +1,27 @@
1
+ import { errorMessage } from "../errors.js";
2
+ // The wrap-up turn of an attempt that ended without an error and without the
3
+ // done tool (at the step cap, or stopped early after the resume), unless the
4
+ // run no longer wants it: cancelled, timed out or past its spend limit, which
5
+ // all abort the signal.
6
+ export function pendingWrapUp(attempt, ended, signal) {
7
+ if (!attempt.wrapUp || signal.aborted)
8
+ return undefined;
9
+ return ended === "step_cap" || ended === "stopped_early" ? attempt.wrapUp : undefined;
10
+ }
11
+ // The attempt's outcome after the turn. The attempt had finished, so a turn
12
+ // that fails keeps what it reported and spent but neither fails the task nor
13
+ // moves it to the next model; the error is recorded in the outcome.
14
+ export async function wrapUp(before, turn) {
15
+ try {
16
+ const { error, ...after } = outcomeOf(await turn());
17
+ const findings = Math.max(0, after.findings.length - before.findings.length);
18
+ return { ...after, wrappedUp: { findings, ...(error ? { error: error.message } : {}) } };
19
+ }
20
+ catch (error) {
21
+ return { ...before, wrappedUp: { findings: 0, error: errorMessage(error) } };
22
+ }
23
+ }
24
+ export function outcomeOf(attempt) {
25
+ const { wrapUp: _turn, ...outcome } = attempt;
26
+ return outcome;
27
+ }
@@ -1,6 +1,6 @@
1
1
  import type { LineRange, Severity } from "../domain.js";
2
2
  import type { SarifRun } from "./schema.js";
3
- interface SarifTool {
3
+ export interface SarifTool {
4
4
  name: string;
5
5
  slug: string;
6
6
  version?: string;
@@ -13,6 +13,8 @@ export interface SarifCandidate {
13
13
  ruleId: string;
14
14
  title: string;
15
15
  body: string;
16
+ message: string;
17
+ security: boolean;
16
18
  }
17
19
  export interface SarifCandidates {
18
20
  tool: SarifTool;
@@ -24,4 +26,3 @@ export interface SarifCandidates {
24
26
  };
25
27
  }
26
28
  export declare function sarifCandidates(run: SarifRun): SarifCandidates;
27
- export {};
@@ -40,6 +40,8 @@ export function sarifCandidates(run) {
40
40
  ruleId,
41
41
  title: rule?.shortDescription?.text?.trim() || rule?.name || ruleId,
42
42
  body: bodyOf(text, ruleId, rule, tool),
43
+ message: text,
44
+ security: [...(result.properties?.tags ?? []), ...(rule?.properties?.tags ?? [])].some((tag) => tag.toLowerCase() === "security"),
43
45
  };
44
46
  const snippet = region.snippet?.text?.trim();
45
47
  if (snippet)
@@ -0,0 +1,35 @@
1
+ import type { FileDiff, LineRange, Severity } from "../domain.js";
2
+ import { type SarifTool } from "./candidates.js";
3
+ import type { SarifLog } from "./schema.js";
4
+ export declare const EVIDENCE_MARGIN_LINES = 10;
5
+ export declare const MAX_EVIDENCE_PER_BUNDLE = 20;
6
+ export declare const MAX_EVIDENCE_MESSAGE_CHARS = 300;
7
+ export interface AnalyzerResult {
8
+ tool: SarifTool;
9
+ file: string;
10
+ lines: LineRange;
11
+ severity: Severity;
12
+ ruleId: string;
13
+ message: string;
14
+ security: boolean;
15
+ onChange: boolean;
16
+ }
17
+ export interface AnalyzerEvidenceUse {
18
+ tool: string;
19
+ version?: string;
20
+ results: number;
21
+ bundles: string[];
22
+ }
23
+ interface FileGroup {
24
+ label: string;
25
+ files: readonly FileDiff[];
26
+ }
27
+ export interface AnalyzerEvidence {
28
+ forBundle(bundle: FileGroup): readonly AnalyzerResult[];
29
+ warnings: string[];
30
+ }
31
+ export declare function analyzerEvidence(logs: readonly SarifLog[], bundles: readonly FileGroup[]): AnalyzerEvidence;
32
+ export declare function evidenceUses(evidence: AnalyzerEvidence, bundles: readonly FileGroup[]): AnalyzerEvidenceUse[];
33
+ export declare function changedLines(diffs: readonly FileDiff[]): Map<string, LineRange[]>;
34
+ export declare function overlaps(lines: LineRange, range: LineRange, margin: number): boolean;
35
+ export {};
@@ -0,0 +1,128 @@
1
+ import { sarifCandidates } from "./candidates.js";
2
+ // Analyzer results shown to reviewers as evidence (ADR-0042): a lead the
3
+ // reviewer confirms in the code, never a finding of its own.
4
+ // A result just outside a hunk is often what the change makes reachable.
5
+ export const EVIDENCE_MARGIN_LINES = 10;
6
+ export const MAX_EVIDENCE_PER_BUNDLE = 20;
7
+ export const MAX_EVIDENCE_MESSAGE_CHARS = 300;
8
+ const noEvidence = { forBundle: () => [], warnings: [] };
9
+ export function analyzerEvidence(logs, bundles) {
10
+ if (logs.length === 0)
11
+ return noEvidence;
12
+ const windows = changedLines(bundles.flatMap((b) => b.files));
13
+ const near = [];
14
+ const counts = new Map();
15
+ const seen = new Set();
16
+ for (const log of logs) {
17
+ for (const run of log.runs) {
18
+ const { tool, candidates, skipped } = sarifCandidates(run);
19
+ const count = counts.get(tool.name) ?? { near: 0, given: 0, away: 0, skipped: 0 };
20
+ counts.set(tool.name, count);
21
+ count.skipped += skipped.noLocation + skipped.unsupportedUri + skipped.noMessage;
22
+ for (const candidate of candidates) {
23
+ const key = [tool.name, candidate.ruleId, candidate.file, candidate.lines.start].join("\0");
24
+ if (seen.has(key))
25
+ continue;
26
+ seen.add(key);
27
+ const result = placed(tool, candidate, windows.get(candidate.file) ?? []);
28
+ if (!result) {
29
+ count.away += 1;
30
+ continue;
31
+ }
32
+ count.near += 1;
33
+ near.push(result);
34
+ }
35
+ }
36
+ }
37
+ near.sort(byRelevance);
38
+ const kept = new Set();
39
+ for (const bundle of bundles) {
40
+ const files = new Set(bundle.files.map((f) => f.newPath));
41
+ for (const r of near.filter((r) => files.has(r.file)).slice(0, MAX_EVIDENCE_PER_BUNDLE)) {
42
+ kept.add(r);
43
+ const count = counts.get(r.tool.name);
44
+ if (count)
45
+ count.given += 1;
46
+ }
47
+ }
48
+ const given = near.filter((r) => kept.has(r));
49
+ return {
50
+ // A file is in one bundle, so a task never sees more than its bundle's cap.
51
+ forBundle: (bundle) => {
52
+ const files = new Set(bundle.files.map((f) => f.newPath));
53
+ return given.filter((r) => files.has(r.file));
54
+ },
55
+ warnings: [...counts].flatMap(([tool, c]) => evidenceWarning(tool, c)),
56
+ };
57
+ }
58
+ function placed(tool, candidate, ranges) {
59
+ const { lines } = candidate;
60
+ const onChange = ranges.some((r) => overlaps(lines, r, 0));
61
+ if (!onChange && !ranges.some((r) => overlaps(lines, r, EVIDENCE_MARGIN_LINES)))
62
+ return undefined;
63
+ return {
64
+ tool,
65
+ file: candidate.file,
66
+ lines,
67
+ severity: candidate.severity,
68
+ ruleId: candidate.ruleId,
69
+ message: candidate.message.slice(0, MAX_EVIDENCE_MESSAGE_CHARS),
70
+ security: candidate.security,
71
+ onChange,
72
+ };
73
+ }
74
+ const SEVERITY_ORDER = { critical: 0, warning: 1, suggestion: 2 };
75
+ function byRelevance(a, b) {
76
+ return (Number(b.onChange) - Number(a.onChange) ||
77
+ SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity] ||
78
+ Number(b.security) - Number(a.security) ||
79
+ (a.file < b.file ? -1 : a.file > b.file ? 1 : 0) ||
80
+ a.lines.start - b.lines.start ||
81
+ (a.ruleId < b.ruleId ? -1 : a.ruleId > b.ruleId ? 1 : 0));
82
+ }
83
+ // The new-side lines each hunk covers, context included.
84
+ export function evidenceUses(evidence, bundles) {
85
+ const uses = new Map();
86
+ for (const bundle of bundles) {
87
+ for (const r of evidence.forBundle(bundle)) {
88
+ const use = uses.get(r.tool.name) ?? {
89
+ tool: r.tool.name,
90
+ ...(r.tool.version ? { version: r.tool.version } : {}),
91
+ results: 0,
92
+ bundles: [],
93
+ };
94
+ use.results += 1;
95
+ if (!use.bundles.includes(bundle.label))
96
+ use.bundles.push(bundle.label);
97
+ uses.set(r.tool.name, use);
98
+ }
99
+ }
100
+ return [...uses.values()];
101
+ }
102
+ export function changedLines(diffs) {
103
+ const windows = new Map();
104
+ for (const diff of diffs) {
105
+ const ranges = diff.hunks
106
+ .filter((h) => h.newLines > 0)
107
+ .map((h) => ({ start: h.newStart, end: h.newStart + h.newLines - 1 }));
108
+ if (ranges.length > 0)
109
+ windows.set(diff.newPath, ranges);
110
+ }
111
+ return windows;
112
+ }
113
+ export function overlaps(lines, range, margin) {
114
+ return lines.start <= range.end + margin && lines.end >= range.start - margin;
115
+ }
116
+ function evidenceWarning(tool, c) {
117
+ const left = [];
118
+ if (c.near > c.given) {
119
+ left.push(`${c.near - c.given} over the limit of ${MAX_EVIDENCE_PER_BUNDLE} per bundle`);
120
+ }
121
+ if (c.away > 0)
122
+ left.push(`${c.away} away from the change`);
123
+ if (c.skipped > 0)
124
+ left.push(`${c.skipped} without a file, lines or message`);
125
+ if (left.length === 0)
126
+ return [];
127
+ return [`${tool}: gave reviewers ${c.given} result(s) as evidence; left out ${left.join(", ")}`];
128
+ }
@@ -13,6 +13,9 @@ declare const rule: z.ZodObject<{
13
13
  defaultConfiguration: z.ZodOptional<z.ZodObject<{
14
14
  level: z.ZodOptional<z.ZodString>;
15
15
  }, z.core.$loose>>;
16
+ properties: z.ZodCatch<z.ZodOptional<z.ZodObject<{
17
+ tags: z.ZodCatch<z.ZodOptional<z.ZodArray<z.ZodString>>>;
18
+ }, z.core.$loose>>>;
16
19
  }, z.core.$loose>;
17
20
  declare const result: z.ZodObject<{
18
21
  ruleId: z.ZodOptional<z.ZodString>;
@@ -36,6 +39,9 @@ declare const result: z.ZodObject<{
36
39
  }, z.core.$loose>>;
37
40
  }, z.core.$loose>>;
38
41
  }, z.core.$loose>>>;
42
+ properties: z.ZodCatch<z.ZodOptional<z.ZodObject<{
43
+ tags: z.ZodCatch<z.ZodOptional<z.ZodArray<z.ZodString>>>;
44
+ }, z.core.$loose>>>;
39
45
  }, z.core.$loose>;
40
46
  declare const sarifRunSchema: z.ZodObject<{
41
47
  tool: z.ZodObject<{
@@ -56,6 +62,9 @@ declare const sarifRunSchema: z.ZodObject<{
56
62
  defaultConfiguration: z.ZodOptional<z.ZodObject<{
57
63
  level: z.ZodOptional<z.ZodString>;
58
64
  }, z.core.$loose>>;
65
+ properties: z.ZodCatch<z.ZodOptional<z.ZodObject<{
66
+ tags: z.ZodCatch<z.ZodOptional<z.ZodArray<z.ZodString>>>;
67
+ }, z.core.$loose>>>;
59
68
  }, z.core.$loose>>>;
60
69
  }, z.core.$loose>;
61
70
  }, z.core.$loose>;
@@ -81,6 +90,9 @@ declare const sarifRunSchema: z.ZodObject<{
81
90
  }, z.core.$loose>>;
82
91
  }, z.core.$loose>>;
83
92
  }, z.core.$loose>>>;
93
+ properties: z.ZodCatch<z.ZodOptional<z.ZodObject<{
94
+ tags: z.ZodCatch<z.ZodOptional<z.ZodArray<z.ZodString>>>;
95
+ }, z.core.$loose>>>;
84
96
  }, z.core.$loose>>>;
85
97
  }, z.core.$loose>;
86
98
  declare const sarifLogSchema: z.ZodObject<{
@@ -104,6 +116,9 @@ declare const sarifLogSchema: z.ZodObject<{
104
116
  defaultConfiguration: z.ZodOptional<z.ZodObject<{
105
117
  level: z.ZodOptional<z.ZodString>;
106
118
  }, z.core.$loose>>;
119
+ properties: z.ZodCatch<z.ZodOptional<z.ZodObject<{
120
+ tags: z.ZodCatch<z.ZodOptional<z.ZodArray<z.ZodString>>>;
121
+ }, z.core.$loose>>>;
107
122
  }, z.core.$loose>>>;
108
123
  }, z.core.$loose>;
109
124
  }, z.core.$loose>;
@@ -129,6 +144,9 @@ declare const sarifLogSchema: z.ZodObject<{
129
144
  }, z.core.$loose>>;
130
145
  }, z.core.$loose>>;
131
146
  }, z.core.$loose>>>;
147
+ properties: z.ZodCatch<z.ZodOptional<z.ZodObject<{
148
+ tags: z.ZodCatch<z.ZodOptional<z.ZodArray<z.ZodString>>>;
149
+ }, z.core.$loose>>>;
132
150
  }, z.core.$loose>>>;
133
151
  }, z.core.$loose>>;
134
152
  }, z.core.$loose>;
@@ -4,6 +4,12 @@ import { errorMessage, OcraError } from "../errors.js";
4
4
  // far more than this, and none of it is trusted beyond what is checked here.
5
5
  // https://docs.oasis-open.org/sarif/sarif/v2.1.0/sarif-v2.1.0.html
6
6
  const message = z.looseObject({ text: z.string().optional() });
7
+ // Tags such as "security" and CWE ids; a log that writes them in another
8
+ // shape loses them, never the result.
9
+ const properties = z
10
+ .looseObject({ tags: z.array(z.string()).optional().catch(undefined) })
11
+ .optional()
12
+ .catch(undefined);
7
13
  const region = z.looseObject({
8
14
  startLine: z.int().positive(),
9
15
  endLine: z.int().positive().optional(),
@@ -26,6 +32,7 @@ const rule = z.looseObject({
26
32
  fullDescription: message.optional(),
27
33
  helpUri: z.string().optional(),
28
34
  defaultConfiguration: z.looseObject({ level: z.string().optional() }).optional(),
35
+ properties,
29
36
  });
30
37
  const result = z.looseObject({
31
38
  ruleId: z.string().optional(),
@@ -33,6 +40,7 @@ const result = z.looseObject({
33
40
  level: z.string().optional(),
34
41
  message,
35
42
  locations: z.array(location).optional(),
43
+ properties,
36
44
  });
37
45
  const sarifRunSchema = z.looseObject({
38
46
  tool: z.looseObject({
@@ -1,5 +1,6 @@
1
1
  export declare const SECRET_PATTERNS: string[];
2
2
  export declare const ENV_TEMPLATE_PATTERNS: string[];
3
3
  export declare const NON_REVIEWABLE_EXTENSIONS: string[];
4
+ export declare const TEXT_EXTENSIONS: string[];
4
5
  export declare const GENERATED_PATTERNS: string[];
5
6
  export declare const MIGRATION_PATTERNS: string[];