@open-cr-agent/core 0.7.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 (122) 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 +10 -5
  4. package/dist/agent/settings.js +22 -8
  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/chat/answer.d.ts +10 -0
  12. package/dist/chat/answer.js +26 -0
  13. package/dist/chat/prompt.d.ts +22 -0
  14. package/dist/chat/prompt.js +65 -0
  15. package/dist/contracts.d.ts +27 -0
  16. package/dist/contracts.js +10 -0
  17. package/dist/domain.d.ts +7 -0
  18. package/dist/domain.js +2 -0
  19. package/dist/index.d.ts +10 -7
  20. package/dist/index.js +4 -4
  21. package/dist/internal.d.ts +8 -3
  22. package/dist/internal.js +8 -3
  23. package/dist/judge/judge.d.ts +1 -1
  24. package/dist/judge/judge.js +10 -13
  25. package/dist/judge/prompt.d.ts +1 -1
  26. package/dist/judge/prompt.js +10 -1
  27. package/dist/judge/verdict.d.ts +2 -1
  28. package/dist/judge/verdict.js +4 -2
  29. package/dist/knowledge/learning.d.ts +21 -0
  30. package/dist/knowledge/learning.js +1 -0
  31. package/dist/knowledge/paths.d.ts +1 -0
  32. package/dist/knowledge/paths.js +18 -0
  33. package/dist/knowledge/select.d.ts +15 -0
  34. package/dist/knowledge/select.js +116 -0
  35. package/dist/knowledge/terms.d.ts +21 -0
  36. package/dist/knowledge/terms.js +153 -0
  37. package/dist/learn/draft.d.ts +21 -0
  38. package/dist/learn/draft.js +126 -0
  39. package/dist/{pipeline → matrix}/matrix.d.ts +1 -2
  40. package/dist/{pipeline → matrix}/matrix.js +1 -1
  41. package/dist/pipeline/answer.d.ts +16 -0
  42. package/dist/pipeline/answer.js +29 -0
  43. package/dist/pipeline/assemble-report.d.ts +2 -6
  44. package/dist/pipeline/assemble-report.js +38 -22
  45. package/dist/pipeline/check-stage.js +31 -11
  46. package/dist/pipeline/context.d.ts +2 -1
  47. package/dist/pipeline/context.js +19 -3
  48. package/dist/pipeline/coverage.d.ts +1 -1
  49. package/dist/pipeline/execute-stage.d.ts +5 -5
  50. package/dist/pipeline/execute-stage.js +27 -30
  51. package/dist/pipeline/execute.d.ts +12 -7
  52. package/dist/pipeline/execute.js +40 -55
  53. package/dist/pipeline/filter-stage.js +2 -0
  54. package/dist/pipeline/imports.js +2 -16
  55. package/dist/pipeline/learnings.d.ts +7 -0
  56. package/dist/pipeline/learnings.js +20 -0
  57. package/dist/pipeline/options.d.ts +22 -1
  58. package/dist/pipeline/options.js +32 -0
  59. package/dist/pipeline/plan-output.d.ts +7 -0
  60. package/dist/pipeline/plan-output.js +9 -1
  61. package/dist/pipeline/plan.d.ts +14 -8
  62. package/dist/pipeline/plan.js +60 -8
  63. package/dist/pipeline/preview.d.ts +5 -4
  64. package/dist/pipeline/preview.js +20 -27
  65. package/dist/pipeline/run.js +23 -47
  66. package/dist/pipeline/task-prompt.d.ts +17 -0
  67. package/dist/pipeline/task-prompt.js +44 -0
  68. package/dist/pipeline/task.d.ts +3 -0
  69. package/dist/pipeline/task.js +3 -1
  70. package/dist/pipeline/walkthrough-stage.d.ts +9 -0
  71. package/dist/pipeline/walkthrough-stage.js +20 -0
  72. package/dist/report/output-schema.d.ts +39 -0
  73. package/dist/report/output-schema.js +31 -2
  74. package/dist/report/output.js +33 -0
  75. package/dist/report/report.d.ts +34 -2
  76. package/dist/report/report.js +29 -0
  77. package/dist/review/impact.d.ts +21 -4
  78. package/dist/review/impact.js +186 -28
  79. package/dist/review/plan-phase.d.ts +1 -1
  80. package/dist/review/plan-phase.js +13 -12
  81. package/dist/review/prompt-text.d.ts +1 -1
  82. package/dist/review/prompt-text.js +84 -20
  83. package/dist/review/prompt.d.ts +6 -0
  84. package/dist/review/prompt.js +57 -2
  85. package/dist/review/tools.d.ts +1 -0
  86. package/dist/review/tools.js +1 -0
  87. package/dist/runtime/attempt.d.ts +12 -0
  88. package/dist/runtime/attempt.js +21 -1
  89. package/dist/runtime/chain-runner.d.ts +2 -2
  90. package/dist/runtime/failback.d.ts +2 -2
  91. package/dist/runtime/failback.js +29 -12
  92. package/dist/runtime/tools.js +11 -0
  93. package/dist/runtime/wrap-up.d.ts +6 -0
  94. package/dist/runtime/wrap-up.js +27 -0
  95. package/dist/sarif/candidates.d.ts +3 -2
  96. package/dist/sarif/candidates.js +2 -0
  97. package/dist/sarif/evidence.d.ts +42 -0
  98. package/dist/sarif/evidence.js +142 -0
  99. package/dist/sarif/schema.d.ts +18 -0
  100. package/dist/sarif/schema.js +8 -0
  101. package/dist/select/patterns.d.ts +1 -0
  102. package/dist/select/patterns.js +46 -0
  103. package/dist/select/select.d.ts +1 -0
  104. package/dist/select/select.js +18 -1
  105. package/dist/session/resume-read.js +3 -0
  106. package/dist/session/seal.js +5 -0
  107. package/dist/vcs.d.ts +22 -0
  108. package/dist/verify/prompt.d.ts +6 -2
  109. package/dist/verify/prompt.js +13 -4
  110. package/dist/verify/related.d.ts +3 -0
  111. package/dist/verify/related.js +88 -0
  112. package/dist/verify/verify.d.ts +3 -3
  113. package/dist/verify/verify.js +27 -19
  114. package/dist/walkthrough/diagram.d.ts +1 -0
  115. package/dist/walkthrough/diagram.js +49 -0
  116. package/dist/walkthrough/prompt.d.ts +19 -0
  117. package/dist/walkthrough/prompt.js +62 -0
  118. package/dist/walkthrough/walkthrough.d.ts +27 -0
  119. package/dist/walkthrough/walkthrough.js +71 -0
  120. package/package.json +3 -3
  121. package/dist/agent/budget.d.ts +0 -12
  122. package/dist/agent/budget.js +0 -27
@@ -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,42 @@
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 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[];
39
+ export declare function evidenceUses(evidence: AnalyzerEvidence, bundles: readonly FileGroup[]): AnalyzerEvidenceUse[];
40
+ export declare function changedLines(diffs: readonly FileDiff[]): Map<string, LineRange[]>;
41
+ export declare function overlaps(lines: LineRange, range: LineRange, margin: number): boolean;
42
+ export {};
@@ -0,0 +1,142 @@
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
+ 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
+ }
97
+ // The new-side lines each hunk covers, context included.
98
+ export function evidenceUses(evidence, bundles) {
99
+ const uses = new Map();
100
+ for (const bundle of bundles) {
101
+ for (const r of evidence.forBundle(bundle)) {
102
+ const use = uses.get(r.tool.name) ?? {
103
+ tool: r.tool.name,
104
+ ...(r.tool.version ? { version: r.tool.version } : {}),
105
+ results: 0,
106
+ bundles: [],
107
+ };
108
+ use.results += 1;
109
+ if (!use.bundles.includes(bundle.label))
110
+ use.bundles.push(bundle.label);
111
+ uses.set(r.tool.name, use);
112
+ }
113
+ }
114
+ return [...uses.values()];
115
+ }
116
+ export function changedLines(diffs) {
117
+ const windows = new Map();
118
+ for (const diff of diffs) {
119
+ const ranges = diff.hunks
120
+ .filter((h) => h.newLines > 0)
121
+ .map((h) => ({ start: h.newStart, end: h.newStart + h.newLines - 1 }));
122
+ if (ranges.length > 0)
123
+ windows.set(diff.newPath, ranges);
124
+ }
125
+ return windows;
126
+ }
127
+ export function overlaps(lines, range, margin) {
128
+ return lines.start <= range.end + margin && lines.end >= range.start - margin;
129
+ }
130
+ function evidenceWarning(tool, c) {
131
+ const left = [];
132
+ if (c.near > c.given) {
133
+ left.push(`${c.near - c.given} over the limit of ${MAX_EVIDENCE_PER_BUNDLE} per bundle`);
134
+ }
135
+ if (c.away > 0)
136
+ left.push(`${c.away} away from the change`);
137
+ if (c.skipped > 0)
138
+ left.push(`${c.skipped} without a file, lines or message`);
139
+ if (left.length === 0)
140
+ return [];
141
+ return [`${tool}: gave reviewers ${c.given} result(s) as evidence; left out ${left.join(", ")}`];
142
+ }
@@ -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[];
@@ -99,6 +99,52 @@ export const NON_REVIEWABLE_EXTENSIONS = [
99
99
  "db",
100
100
  "sqlite",
101
101
  ];
102
+ // Names that say source or text: such a file diffing as binary is worth a
103
+ // warning (select.ts). Not exhaustive; a miss only loses the warning.
104
+ export const TEXT_EXTENSIONS = [
105
+ "c",
106
+ "cc",
107
+ "cpp",
108
+ "cs",
109
+ "css",
110
+ "cxx",
111
+ "dart",
112
+ "ex",
113
+ "exs",
114
+ "go",
115
+ "gradle",
116
+ "h",
117
+ "hpp",
118
+ "html",
119
+ "java",
120
+ "js",
121
+ "json",
122
+ "jsx",
123
+ "kt",
124
+ "kts",
125
+ "lua",
126
+ "m",
127
+ "md",
128
+ "mjs",
129
+ "cjs",
130
+ "php",
131
+ "pl",
132
+ "py",
133
+ "rb",
134
+ "rs",
135
+ "scala",
136
+ "scss",
137
+ "sh",
138
+ "sql",
139
+ "swift",
140
+ "toml",
141
+ "ts",
142
+ "tsx",
143
+ "vue",
144
+ "xml",
145
+ "yaml",
146
+ "yml",
147
+ ];
102
148
  export const GENERATED_PATTERNS = [
103
149
  "**/package-lock.json",
104
150
  "**/npm-shrinkwrap.json",
@@ -27,3 +27,4 @@ export declare const defaultSelectionPolicy: SelectionPolicy;
27
27
  export declare function isSecretPath(path: string): boolean;
28
28
  export declare function foldPath(path: string): string;
29
29
  export declare function selectFiles(diffs: readonly FileDiff[], policy?: SelectionPolicy): FileDecision[];
30
+ export declare function binaryTextWarning(decisions: readonly FileDecision[]): string | undefined;
@@ -1,6 +1,6 @@
1
1
  import picomatch from "picomatch";
2
2
  import { z } from "zod";
3
- import { ENV_TEMPLATE_PATTERNS, GENERATED_PATTERNS, MIGRATION_PATTERNS, NON_REVIEWABLE_EXTENSIONS, SECRET_PATTERNS, } from "./patterns.js";
3
+ import { ENV_TEMPLATE_PATTERNS, GENERATED_PATTERNS, MIGRATION_PATTERNS, NON_REVIEWABLE_EXTENSIONS, SECRET_PATTERNS, TEXT_EXTENSIONS, } from "./patterns.js";
4
4
  export const exclusionReasonSchema = z.enum([
5
5
  "binary",
6
6
  "secret",
@@ -20,6 +20,8 @@ const isSecret = picomatch(SECRET_PATTERNS, { ...globOptions, ignore: ENV_TEMPLA
20
20
  const isGenerated = picomatch(GENERATED_PATTERNS, globOptions);
21
21
  const isMigration = picomatch(MIGRATION_PATTERNS, globOptions);
22
22
  const nonReviewableExtensions = new Set(NON_REVIEWABLE_EXTENSIONS);
23
+ const textExtensions = new Set(TEXT_EXTENSIONS);
24
+ const NAMED_FILES = 3;
23
25
  // The raw path is matched too: NFKC can fold a character into "/", which a
24
26
  // pattern's "*" matches only in the raw path.
25
27
  export function isSecretPath(path) {
@@ -65,6 +67,21 @@ function exclusionReason(diff, policy, isUserExcluded, isUserIncluded) {
65
67
  return "too_large";
66
68
  return undefined;
67
69
  }
70
+ // A file whose name says text diffs as binary because of its size or a
71
+ // .gitattributes entry, and an adapter that reads attributes from the
72
+ // reviewed tree (an old git) lets the change set them: worth saying, since
73
+ // binary files are not reviewed.
74
+ export function binaryTextWarning(decisions) {
75
+ const paths = decisions
76
+ .filter((d) => !d.selected && d.reason === "binary" && d.diff.kind !== "deleted")
77
+ .map((d) => d.diff.newPath)
78
+ .filter((path) => textExtensions.has(extension(path)));
79
+ if (paths.length === 0)
80
+ return undefined;
81
+ const more = paths.length > NAMED_FILES ? ` and ${paths.length - NAMED_FILES} more` : "";
82
+ return (`${paths.length} file(s) not reviewed as binary although their names say text ` +
83
+ `(a .gitattributes entry or their size): ${paths.slice(0, NAMED_FILES).join(", ")}${more}`);
84
+ }
68
85
  function matcher(patterns) {
69
86
  return patterns.length === 0 ? () => false : picomatch([...patterns], globOptions);
70
87
  }
@@ -72,6 +72,9 @@ export async function readResumedRun(sessionsDir, runId, sealKey, warn = () => {
72
72
  if (b.success)
73
73
  groups = b.data.groups;
74
74
  }
75
+ if (sealed === 0 && unsealed === 0) {
76
+ throw new OcraError("INPUT_INVALID", `--resume: the session log of ${runId} is empty, so there is nothing to reuse`);
77
+ }
75
78
  if (sealed === 0) {
76
79
  throw new OcraError("INPUT_INVALID", `--resume: the session of ${runId} was not written by ocra on this machine, so none of it is reused`);
77
80
  }
@@ -9,6 +9,11 @@ export const SEAL_KEY = /^[0-9a-f]{64}$/;
9
9
  const SEALED = /,"seal":"([0-9a-f]{64})"\}$/;
10
10
  /** The serialized JSON object with its seal as a last field. */
11
11
  export function sealLine(key, runId, line) {
12
+ // The seal goes in before the closing brace; any other line would come out
13
+ // as something unsealLine, and every JSON reader, rejects.
14
+ if (!line.startsWith("{") || !line.endsWith("}")) {
15
+ throw new Error("sealLine: the line is not a serialized JSON object");
16
+ }
12
17
  return `${line.slice(0, -1)},"seal":"${mac(key, runId, line).toString("hex")}"}`;
13
18
  }
14
19
  /** The line as it was before sealing; undefined unless key sealed it for this run. */